Reputation: 31
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
Upvotes: 1
Views: 2030
Reputation: 88499
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)
Upvotes: 1
Reputation: 986
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
Upvotes: 0