在Django REST Framework中的CreateAPIView中的create()之后返回不同的序列化器

时间:2019-06-04 07:32:57

标签: django django-rest-framework

我正在使用 Django 2.2 Django REST Framework

我必须为同一模型使用序列化器。

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序列化程序用于列出订单或订单明细视图,OrderCreateSerializer用于创建新的订单实例。

视图是

class CreateOrderView(generics.CreateAPIView):
    serializer_class = OrderCreateSerializer

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

这很好,因为订单对象正在按预期方式创建。但是返回的值不包含任何数据。

我要在创建订单后使用OrderListSerializer呈现保存的订单详细信息。

创建对象后如何更改序列化程序类?

此外,在对象成功创建后,我还必须触发信号。 触发信号的最佳位置是什么?

3 个答案:

答案 0 :(得分:2)

如下更改 CreateOrderView

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() 返回刚刚创建或更新的实例。因此,我们使用这种方式传递给OrderListSerializer并返回相应的响应。

答案 1 :(得分:0)

您可以在这里使用几种方法。首先,

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)

替代方法是条件if语句,其中

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

答案 2 :(得分:0)

您可以覆盖create(),然后返回所需的任何内容:

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)
(...)