Use corresponding serializer class for different request method in Django Rest Framework

Django Rest Framework(DRF) provide a extremely convenience way to develop RESTful apps. Such as generics module, which contains many useful APIView based on the request method.

But I get it in trouble when it comes to serializer class with these generics views. Like code below:

It’s a common situation to have foreign key in the model. Whenever we create a User(without nested creation of Organization) or update a User’s org property, we’d like simply provide a org_uuid to the view. But when we get or list information of User instances, we’re willing to see more information than just a org_uuid. So the creation or update should have different serializer with list or view method. I usually create at least two serializer class for the model class like User. Here is the serializer classes:

As we can see above, it can expand user’s organization information by using nested serializer when list or view users information. On the other hand, a org_uuid is enough to create or update an User instance.

That’s go back to generics module. Based on the principle of REST, maybe the generics.ListCreateAPIViewandgenerics.RetrieveUpdateAPIVieware the most commonly used View, which are designed based on the request method too. DRF has done so well in the View, but in the serializer it do not go further. So I made the recipe below:

Notice: The MethodSerializerView should placed before generics’s view, so it can override the get_serializer_class method.

Finally, we have multiple choices for serializer when dealing with generics’s view, all based on request method 😀.