I am confused regarding the DRF Serializer Documentation:
For serializers, it was mentioned that,
If your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if Comment was a Django model, the methods might look like this:
def create(self, validated_data):
return Comment.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.email = validated_data.get('email', instance.email)
instance.content = validated_data.get('content', instance.content)
instance.created = validated_data.get('created', instance.created)
instance.save()
return instance
From serializers.py code, it seems that .save() will update the instance in the database.
However, it was later mentioned,
Now when deserializing data, we can call .save() to return an object instance, based on the validated data.
comment = serializer.save()
Calling .save() will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class:
# .save() will create a new instance.
serializer = CommentSerializer(data=data)
# .save() will update the existing `comment` instance.
serializer = CommentSerializer(comment, data=data)
It seems that calling serializer.save() in views.py will update the 'comment' instance in the database. Calling instance.save() in serializers.py will also update the 'comment' instance in the database.
My question is if there is a difference between the two methods of saving / updating an instance to the database?