Why `create()` method of django rest framework serializer return a value?

3.9k views Asked by At

I don't understand why the create() method in DRF serializer has to return a value. E.g.:

class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer()

class Meta:
    model = User
    fields = ('username', 'email', 'profile')

def create(self, validated_data):
    profile_data = validated_data.pop('profile')
    user = User.objects.create(**validated_data)
    Profile.objects.create(user=user, **profile_data)
    return user

Would not be sufficient save User istance without returning values?

1

There are 1 answers

2
Rahul Gupta On BEST ANSWER

It returns the created instance so that the created user can be used anywhere if need be. There are often use cases where you might need the user or any other generic saved instance somewhere in your code. So upon saving always, the saved instance is returned so that the programmer can use it whenever need be.