1

Hello guys and girls,

Just having a little issue with Django Rest Framework : let's say I have a Book class :

models.py

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

serializers.py

class BooksSerializer (serializers.ModelSerializer)
    class Meta:
        model = Books
        fields = ['id', 'title']

And now I want to allow the create method only until I have 30 books in database.

This is the kind of code I have until now but it isn't working so far, how would you recommend me to proceed ? I can override the create method from the ModelViewSet class right ?

views.py

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

    def create(self, serializer):
        number_of_books = queryset.count()
        if number of book < 30:
            serializer.save()
        else:
            response = {'message': 'You can't create more than 30 values'}
            return Response(response, status=status.HTTP_400_BAD_REQUEST)

Thank you in advance for your help

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.