Search code examples
django-rest-frameworkdjango-viewsdjango-serializer

where should we write our CURD Operation in modelviewset or viewsets or in Serializer in django rest framework


If we observe carefully, we have both CURD Operation can be performed in viewset

As per example in docs

class UserViewSet(viewsets.ViewSet):
    """
    Example empty viewset demonstrating the standard
    actions that will be handled by a router class.

    If you're using format suffixes, make sure to also include
    the `format=None` keyword argument for each action.
    """

    def list(self, request):
        pass

    def create(self, request):
        pass

    def retrieve(self, request, pk=None):
        pass

    def update(self, request, pk=None):
        pass

    def partial_update(self, request, pk=None):
        pass

    def destroy(self, request, pk=None):
        pass

Here is serializer example

class CommentSerializer(serializers.Serializer):
    email = serializers.EmailField()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()

    def create(self, validated_data):
        return Comment(**validated_data)

    def update(self, instance, validated_data):
        instance.email = validated_data.get('email', instance.email)
        instance.content = validated_data.get('content', instance.content)
        instance.created = validated_data.get('created', instance.created)
        return instance

Assume that we can get validated data, just skip that, the question is where should I perform CRUD Operation, whats the tradeoffs of using each. What's the best practice, why reasons behind the approach, this would be of good help for a lot of people.


Solution

  • It depends on our requirements.

    CRUD operations are handled in viewsets. This is the one sentance answer.

    In the code you have given :

    class CommentSerializer(serializers.Serializer):

    since this is a normal serializer you have to write create and update method here. You can use ModelSerializer which saves you from writing definition for create and update .like this.

    Class CommentSerializer(serializer.ModelSerializer):
          class Meta:
              fields = '__all__'
              model = Comment 
    

    Then you can write the viewset using ModelViewSet which provides you default implementation of all the CRUD operations.

    Class CommentViewSet(viewset.ModelViewSet):
          serializer_class = CommentSerializer
          queryset         = Comment.objects.all()
    

    now the CommentViewSet lets you do all the CRUD operations.thats why we use ModelViewSet.

    If you need to do extra actions during the time of creation or updation you can simply override the create() and update() methods in serializer.
    This is when we write CRUD in serializer - to do extra actions.