Ed Campion Ed Campion - 4 years ago 124
Python Question

Django Rest Framework - Serializing relationship differently for GET and POST

Given 2 main models: TransportOrder and Company with a many to many relationship through TransportOrderConsumer. I would like to achieve the following.

GET TransportOrder:

TransportOrder fields are listed as well as a list of hyperlinks to consumers.
I've accomplished this through the below relationship on the Company and serializer

consumers = models.ManyToManyField(Company, through = "TransportOrderConsumer")

class TransportOrderReadSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = TransportOrder
# fields = ('id', 'producer_system_code', 'status','producer', 'created_at')
fields = (
# read_only_fields = ('updated_at')

POST Transport Order:
In the POST serializer, I want to nest a TransportOrderConsumerSerializer but call it "consumers" so that there is consistency between the get and post calls.

To sum up the problem, is it possible to, in one serializer have consumers relate to Company objects, and in the second (the POST) have the consumers field be a TransportOrderConsumerSerializer?

Answer Source

You would use get_serializer_class to switch on the request type for what serializer you want to use.

Example code:

from rest_framework import viewsets

class MyViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()

    def get_serializer_class(self):
        :return: serializer class based on the request type
        if self.action == 'retrieve':
            return ps.MyModelDetailSerializer
        elif self.action == 'list':
            return ps.MyModelListSerializer
        elif self.action == 'create':
            return ps.MyModelCreateSerializer
            return ps.MyModelUpdateSerializer
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download