如何在Django中创建成功时返回创建的数据

时间:2018-05-30 03:25:26

标签: python django django-rest-framework

在我的Django项目中,我有一个APIView:

class PhysicalServerManualGenerateOrderAPIView(CreateAPIView):
    serializer_class = PhysicalServerManualGenerateOrderSerialzier
    permission_classes = [IsFinanceAdmin, IsSuperAdmin]
    queryset = Order.objects.all() 
PhysicalServerManualGenerateOrderSerialzier中的

class PhysicalServerManualGenerateOrderSerialzier(ModelSerializer):
    ...
    def create(self, validated_data):

        try:
            order = getOrder(user=user, validated_data=validated_data) # there I create the order instance
        except Exception as e:
            order = None

        return order

但我有一个要求,我想在访问APIView成功时返回创建的订单的ID(或其他数据)。

1 个答案:

答案 0 :(得分:0)

如下所示更改您的api,

from rest_framework.response import Response
from rest_framework import status


class PhysicalServerManualGenerateOrderAPIView(CreateAPIView):
    # your code
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)

        sufficent_data = serializer.data  # you will get the serialized data here, which includes the "order_id" too

        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


当您调用self.perform_create(serializer)时,create()类的PhysicalServerManualGenerateOrderSerialzier方法将被调用并返回Order实例。 serializer.data将序列化该实例并使其在API类

中可用