Hello,
I am using viewset, the default viewsets.ModelViewSet.
I am trying to find the best way to hook yourself before the serializer save is called. I want to initialize some variables before serialization is done.
As an example, let's say we have a model:
class Book(models.Model):
number = models.CharField(_("Book number"), max_length=50)
the number is a required field on the model level. At the API level, it either needs to be passed on the request OR the system generates a unique next number for the book.
Option 1:
If i try to overwrite the serialize field:
number = serializers.CharField(max_length=50, required=False)
and just overwrite the create view method:
def perform_create(self, serializer):
if number_is_not set on request:
serializer.save(number=new_generated_number)
else:
This would be most normal in my view, but it does not work. It gives me a field required error (for the number). The required=False is not taken into consideration for me.
Option 2:
i wanted to add the number on the request before validation is done. Found this option, by overwriting the viewset method:
def initialize_request(self, request, *args, **kwargs):
request = super(BookViewSet, self).initialize_request(request, *args, **kwargs)
number = request.DATA.get('number', None)
#Set number in case it is not sent, when creating a new book.
if not number and request.method == 'POST':
request.DATA['number'] = "generated number"
return request
Option 2 works, but somehow it does not feel to be the most proper way. Is there other ways to do this?
Cheers,
Vlad