Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRF create method in viewset or in serializer

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?

like image 727
iserranoe Avatar asked Aug 28 '20 08:08

iserranoe


People also ask

What is difference between APIView and ViewSet?

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.

What is difference between ModelSerializer and serializer?

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 .

What is ViewSet in Django REST?

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'.

When would you use a serializer?

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.

What is the difference between create on viewset and create on Serializer?

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:

How do serializers work in the rest framework?

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.

What is modelviewset in DRF?

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 () ."

What is the use of serializer in DRF Base64?

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.


1 Answers

create method from viewset

This method handles the POST request logic in the view, which by default does:

  • instantiate the serializer with whatever data comes as payload in the request
  • executed the is_valid method on the serializer
  • perform the actual create by calling .save() method on serializer
  • returns the view Response with serialized data and 201 status

You 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 serializer

This 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:

  • in viewset the create method handles request-response flow
  • in serializer the create method handles model instance creation using validated data.
like image 184
Gabriel Muj Avatar answered Sep 29 '22 20:09

Gabriel Muj