Different validation in drf serializer for each request method

Let's say I have a model like this:

class MyModel(models.Model): first_field = models.CharField() second_field = models.CharField() 

and an API view like this:

 class MyModelDetailAPI(GenericAPIView): serializer_class = MyModelSerializer def patch(self, request, *args, **kwargs): # Do the update def post(self, request, *args, **kwargs): # Do the post 

first_field is a field that is only inserted into the POST method (and is required), but the user cannot change its value with each update, so the field in the PATCH method is optional.
How can I write my serializer so that first_field required in POST, but not required for PATCH. Is there a way to dynamically set the required field, so I can still use the DRF verification mechanism? What type of validator dispatcher for each request?
I want something like this, for example:

 class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = { 'POST': ['first_field'] 'PATCH': [] } 
+5
source share
1 answer

I need more space than comments to make my point clear. So here is what I suggest:

  • Different formatting means different serializers.

    So here you have, for example, MyModelSerializer and MyModelCreationSerializer . Either create them yourself, or inherit another and specialize it (if that makes sense).

  • Use the appropriate GenericAPIView hook to return the correct serializer class depending on self.action . A very simple example:

     class MyModelDetailAPI(GenericAPIView): # serializer_class = unneeded as we override the hook below def get_serializer_class(self): if self.action == 'create': return MyModelCreationSerializer return MyModelSerializer 

    The default actions in regular views are documented here , they are:

    • create : POST method on URL base route
    • list : GET method on URL base route
    • retrieve : GET method for object url
    • update : PUT method for object url
    • partial_update : PATCH method for object url
    • destroy : DELETE method for object url
+4
source

All Articles