Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between a Viewsets `create()` and `update()` and a Serializers `create()` and `update()`?

Over here: http://www.django-rest-framework.org/api-guide/viewsets/#modelviewset it says "The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy()."

Over here: http://www.django-rest-framework.org/api-guide/serializers/#modelserializer it says "The ModelSerializer class is the same as a regular Serializer class, except that: It includes simple default implementations of .create() and .update()."

1) Assuming there is a Viewset UserViewSet and router user and serializer UserSerializer. If I sent a POST to /user/ does it call the UserViewSet's create() or the UserSerializer's create()?

2) Suppose UserViewSet has this permission:

class NoCreate(permissions.BasePermission):
    """
    No one can create this object.
    """
    message = 'You do not have permission to complete the action you are trying to perform.'

    def has_permission(self, request, view):
        if view.action == "create":
            return False
        return True

Does the UserSerializer's create() still get called if I send a POST to /user/?

like image 490
SilentDev Avatar asked Mar 06 '17 00:03

SilentDev


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 views and Viewsets?

While regular views act as handlers for HTTP methods, viewsets give you actions, like create or list . The great thing about viewsets is how they make your code consistent and save you from repetition. Every time you write views that should do more than one thing, a viewset is the thing that you want to go for.

What is the use of Serializers?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

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 .


2 Answers

1) Assuming there is a Viewset UserViewSet and router user and serializer UserSerializer. If I sent a POST to /user/ does it call the UserViewSet's create() or the UserSerializer's create()?

Both will be called. The view's create will get the serializer, ensure the provided data are valid, call the serializer's save and will generate the response. The serializer's create will actually perform the instance creation - i.e. write it to the database.

Does the UserSerializer's create() still get called if I send a POST to /user/?

No if the permission is set to the viewset. However, if you want to prevent any creation, you should fine tune your ModelViewSet:

class UserViewSet(mixins.RetrieveModelMixin,
                  mixins.UpdateModelMixin,
                  mixins.DestroyModelMixin,
                  mixins.ListModelMixin,
                  GenericViewSet):

Will contain all the action except the creation.

like image 169
Linovia Avatar answered Oct 22 '22 12:10

Linovia


The .create() and .update() methods in ViewSets are actions that are executed when a request is made. A request with POST method calls ViewSet's .create() method since a request with PUT method or PATCH calls the ViewSet's .update() method.

The .create() and .update() methods of the Serializer are executed by calling the .save() method of the Serializer.

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)

See the Saving Instances documentation for more details.

like image 5
Hugo Brilhante Avatar answered Oct 22 '22 12:10

Hugo Brilhante