[Answered ]-Custom method create in ModelViewset Django Rest Framework

1👍

This is the best way to override and validate the request

from rest_framework.response import Response
from rest_framework import status


class BooksViewset(viewsets.ModelViewSet):
    queryset = Books.objects.all()
    serializer_class = BooksSerializer

    def create(self, request, *args, **kwargs):
        book_count = self.get_queryset().count()
        if book_count >= 30:
            return Response(
                {"message": "Max book create limit exceeded"},
                status=status.HTTP_400_BAD_REQUEST
            )

        return super().create(request, *args, **kwargs)
👤JPG

0👍

what about super charging save() method of Books model?

The idea here is to change the save behaviour of Books model as required, for instance, limiting the amount of books in DB at 30

class Books(models.Model):
    title = models.Charfield(max_length = 50, blank=False)

    def save(self, *args, **kwargs):
        if Books.objects.all().count() < 30:
            super().save(*args, **kwargs)
        else:
            raise TypeError("No more then 30 books, merci pour le libraire")

https://docs.djangoproject.com/en/3.2/topics/db/models/#overriding-predefined-model-methods

Leave a comment