Search code examples
djangoserializationdjango-rest-frameworkdjango-rest-viewsets

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/?


Solution

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