Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return different serializer after create() in CreateAPIView in Django REST Framework

I'm using Django 2.2 and Django REST Framework.

I have to serializers for the same model.

class OrderListSerializer(serializers.ModelSerializer):
    plan = PlanBaseSerializer(read_only=True, many=False)

    class Meta:
        model = Order
        fields = [
            'id', 'name', 'plan', 'pricing',
            'created', 'completed',
        ]


class OrderCreateSerializer(serializers.ModelSerializer):
    plan_pricing = serializers.IntegerField(required=True, write_only=True)

    class Meta:
        model = Order
        fields = [
            'plan_pricing'
        ]

    def create(self, validated_data):
        plan_pricing_ = validated_data.pop('plan_pricing', None)
        try:
            plan_pricing = PlanPricing.objects.get(pk=plan_pricing_)
        except PlanPricing.DoesNotExists:
            raise ValidationError('Plan pricing not available')

        validated_data['plan'] = plan_pricing.plan
        validated_data['amount'] = plan_pricing.price

        return super().create(validated_data)

OrderListSerializer serializer is used for listing orders or order detail view and OrderCreateSerializer is used for creating a new order instance.

The view is

class CreateOrderView(generics.CreateAPIView):
    serializer_class = OrderCreateSerializer

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

This is working fine as the order object is creating as expected. But the returned value contains no data.

I want to use OrderListSerializer to render saved order details after creating the order.

How to change the serializer class after creating the object?

Also, I have to trigger a signal after the object has been successfully created. What is the best place to trigger a signal?

like image 465
Anuj TBE Avatar asked Jun 04 '19 07:06

Anuj TBE


People also ask

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

Which class allows you to automatically create a serializer?

The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields.

What does a serializer return Django?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is mixin DRF?

Mixins. The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as . get() and . post() , directly.


1 Answers

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.

like image 184
JPG Avatar answered Sep 20 '22 16:09

JPG