I don't understand how Django-Rest-Framework serializers work

This may seem like a silly question, but I really feel that the Django-Rest-Framework does not explain very well how this works. Too much black magic that confuses setup instructions (in my opinion).

For example, he says that I can override the creation or update in my serializer. Therefore, when I look at the message, I can send data to a serializer that has a declared update method.

class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel def update(self, instance, validated_data): 

Is an update called only when the model already exists, and we just update some of its data? Or does it cause you to create when you create a new one?

if I have to add this method to this class,

 def create(self, validated_data): return MyObject.objects.create(**validated_data) 

Is this specifically the method that needs to be called to add a new object? and your ability to override should be placed in a serializer, but if not declared, is this the default method with called parameters?

+5
source share
1 answer

Too much black box magic that confuses setup instructions (in my opinion).

If there is something in the documentation that you think can be improved, feel free to send a transfer request with the update. If this seems reasonable, it is likely to be consolidated and appear in a future release.

Or does it invoke create when creating a new one?

create is called when the serializer is not initialized by the model instance, but only data is passed to it. When serializer.save() is called, the serializer checks to see if the instance has been passed and calls create directly, so the model instance is created and stored in the database.

Is only the call updated when the model already exists, and we just update some of its data?

update is called when the serializer is initialized with a model instance (or other object) and serializer.save() called. This is roughly equivalent to Model.objects.update() compared to Model.objects.create() .

Is this specifically the method that must be called to add a new object?

Serializers are designed to be saved (including creating and updating objects) using the central serializer.save() method. This is similar to how a model can be saved or created using the model.save() method.

and your ability to override should be placed in a serializer, but if not declared, is this the default method with parameters that call?

It is recommended to override create and update at the serializer level if you need to change the logic of how to save the model and its associated objects, for example, when working with nested serializers.

+17
source

All Articles