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
- [Answered ]-Cannot overwrite default django database settings
- [Answered ]-How do I edit my serializer create() method to make relationship to nested object in Django REST Framework?
- [Answered ]-Get user OneToOneField fields in ModelForms
- [Answered ]-Django Contact Form send html emails
- [Answered ]-Django: getting m2m values after model_save
Source:stackexchange.com