Search code examples
pythondjangodjango-rest-frameworkdjango-serializer

When to use DRF Serializer's methods .save(), .create(), and .to_internal_value() properly?


On DRF documentation we have that:

.to_internal_value() - For write operations.

.create() - For saving instances.

.save() - To persist the validated data into an object instance.

It seems that we can do the same stuff with any of these.
So what is the best practice to use them?


Solution

  • You can use to_internal_value to modify the data given in the request (like before deserialization) and usually do validations:

    def to_internal_value(self, data):
        try:
             obj_id = data['id']
             return Obj.objects.get(id=obj_id)
        except Obj.DoesNotExist:
            raise serializers.ValidationError(
            'Obj does not exist.'
            )
    

    create() is used when you want to customize the creation of an instance of your model:

    def create(self, validated_data):
        obj = MySerializer(**validated_data)
        obj.really = True
        obj.save()
        return obj
    

    and save() is when you want to persist the created instance in the database.