[Fixed]-Return different serializer after create() in CreateAPIView in Django REST Framework

24👍

Change CreateOrderView as below,

class CreateOrderView(generics.CreateAPIView):
    serializer_class = OrderCreateSerializer

    def perform_create(self, serializer):
        return serializer.save(user=self.request.user)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = self.perform_create(serializer)
        instance_serializer = OrderListSerializer(instance)
        return Response(instance_serializer.data)

serializer.save() returns the instance that just created or updated. So we use that istance to pass to the OrderListSerializer and returning the corresponding response.

👤JPG

1👍

You could overwrite create(), and return whatever you want:

from rest_framework import response, status
(...)
    def create(self, request, *args, **kwargs):
        super().create(request, *args, **kwargs)
        return response.Response(status=status.HTTP_201_CREATED)
(...)

0👍

There are several ways you can use here. First,

class CreateOrderView(generics.ListCreateAPIView):
    serializer_class = OrderCreateSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

    def list(self, *args, **kwargs):
        serializer_class = OrderListSerializer
        serializer = serializer_class(self.get_queryset())
        return Response(serializer.data)

The alternative would be a conditional if statement, where

if self.request.method=='POST':
   self.serializer_class = OrderCreateSerializer
elif self.request.method=='GET':
   self.serializer_class = OrderListSerializer

Leave a comment