This may seem like a dumb question but I really feel like Django-Rest-Framework does not explain really well how it works. There is too much black box magic which confuses the configuration instructions (in my opinion).
For instance, it says I can override create or update within my serializer. So when my view post, I can send data to the serializer which has an update method declared.
class MySerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
def update(self, instance, validated_data):
Does update only get called when the model already exists and we're just updating some of it's data? Or does it call create when it creates a new one?
if I were to add this method to that class,
def create(self, validated_data):
return MyObject.objects.create(**validated_data)
is this specifically the method that must be called in order to add a new object? and your ability to override should be put in the serializer, but if not declared this is the default method with parameters that's being called?
There is too much black box magic which confuses the configuration instructions (in my opinion).
If there is something in the documentation that you think can be improved, feel free to submit a pull request with an update. If it seems reasonable, it will probably be merged and show up in a future release.
Or does it call create when it creates a new one?
create
is called when a serializer is not initialized with a model instance, but only data is passed into it. Once serializer.save()
is called, the serializer check if an instance was passed in and directly calls create
so the model instance is created and saved in the database.
Does update only get called when the model already exists and we're just updating some of it's data?
update
is called when a serializer is initialized with a model instance (or other object) and serializer.save()
is called. This is roughly equivalent to Model.objects.update()
when compared to Model.objects.create()
.
is this specifically the method that must be called in order to add a new object?
Serializers are designed to be saved (including object creation and updating) 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 put in the serializer, but if not declared this is the default method with parameters that's being called?
It is recommended to override create
and update
on the serializer level if you need to change the logic for how a model and its related objects need to be saved, such as when working with nested serializers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With