What is the difference between customizing the "create" method in DRF viewset or customizing it in the serializer? I understand the serializer is responsible to deserialize the data, i.e. the way the data is presented in the POST query; however, I can also create objects in related fields in the serializer.
#views.py
def create(self, request):
pass
#serializer.py
def create(self, validated_data):
return Model.objects.create(**validated_data)
When should I customize views/create vs. serializer/create?
APIView allow us to define functions that match standard HTTP methods like GET, POST, PUT, PATCH, etc. Viewsets allow us to define functions that match to common API object actions like : LIST, CREATE, RETRIEVE, UPDATE, etc.
The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .
Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet . In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
Serialization is the process of transforming data into a format that can be stored or transmitted and then reconstructing it. It's used all the time when developing applications or storing data in databases, in memory, or converting it into files.
I also like to separate both logics from each other, so create on viewset level is for requests that are meant to actually create a record on backend, while the create on serializer level is to create an object from serialized and return for you do what you need with it. This method handles the POST request logic in the view, which by default does:
The serializers in REST framework work very similarly to Django's Form and ModelForm classes. We provide a Serializer class which gives you a powerful, generic way to control the output of your responses, as well as a ModelSerializer class which provides a useful shortcut for creating serializers that deal with model instances and querysets.
The ModelViewSet is what it sounds like: a set of views that lets you take a series of actions on model objects. The DRF docs define it as "a type of class-based View, that does not provide any method handlers such as .get () or .post (), and instead provides actions such as .list () and .create () ."
The serializer facilitates processing of arbitrarily nested JSON structures within HTML. For example, <input name="items [0] [id]" value="5"> will be interpreted as {"items": [ {"id": "5"}]}. DRF-Base64 provides a set of field and model serializers that handles the upload of base64-encoded files.
create
method from viewsetThis method handles the POST
request logic in the view, which by default does:
is_valid
method on the serializer.save()
method on serializerResponse
with serialized data and 201 statusYou don't really need to override the create
method on viewset, if is something that you need to send to the serializer from the view itself you can override perform_create
which by default does serializer.save()
. Eg. if you want to send the user from the request you can do:
def perform_create(self, serializer):
# here you will send `created_by` in the `validated_data`
serializer.save(created_by=self.request.user)
Note: Behind the scene save
method will execute the create
method on serializer with the validated_data
create
method from serializerThis method just creates the actual model instance using the validated_data
. You may override this method in case you need to create related objects, like the following:
def create(self, validated_data):
items_data = validated_data.pop('items')
# similar to Parent.objects.create(**validated_data)
parent = super().create(**validated_data)
for item_data in items_data:
Item.objects.create(parent=parent, **item_data)
return parent
So here you are sending a payload with data regarding the Parent
object but also a list of items
with their representation, so now the create
method will create also the Items and link them with the Parent instance.
To summarize this:
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