[Django]-Serializing and deserializing in Django Rest Framework

4👍

You can add additional serializer with primary key to Courier:

class OrderSerializerForPost(serializers.ModelSerializer):
    courier = serializers.PrimaryKeyRelatedField()

    class Meta:
        model = Order
        fields = (
            "number",
            "courier"
        )

And then use it with your overrided post mehtod…

class OrderList(generics.ListCreateAPIView):

    model = Order
    serializer_class = OrderSerializer

    def post(self, request):
        self.serializer_class = OrderSerializerForPost
        super(OrderList, self).post(request)

Or you can try redefine your get_serializer_class method:

class OrderList(generics.ListCreateAPIView):

    model = Order
    serializer_class = OrderSerializer

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return self.serializer_class
        elif self.request.method == 'POST':
            return OrderSerializerForPost

Leave a comment