在我的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(或其他数据)。
答案 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类