如何在Django REST中手动填充关系模型

2024-06-17 12:57:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我还是Django和DRF的新手。我有两个模型(Policy和Rescue),Rescue通过外键Policy\u id与Policy相关。我可以通过CreateView发布JSON消息并用请求数据填充Policy。但是,需要根据发布到策略的JSON数据的一些计算来填充第二个模型Rescue。救援不能事先公布。我尽力了,但不知道怎么做。你知道吗

这是与嵌套序列化程序有关还是其他原因有关?你知道吗

我试过了

我可以这样尝试吗:在类CreateView中:

class CreateView(generics.CreateAPIView):

    def create(self, request, *args, **kwargs):
        my_serializer = self.get_serializer(data=request.data)
        ...
        # get a policy object based on 'policy_id' against serializer
        my_policy = Policy.objects.get(policy_id=my_serializer.data['policy_id'])
        ...
        ... # some calculations to work out a rescue id, and will be returned and saved.
        Rescue.objects.create(rescue_id='QD1234', policy=my_policy)

Tags: 数据模型selfidjsondatagetrequest
1条回答
网友
1楼 · 发布于 2024-06-17 12:57:19

您可以使用泛型CreateAPIView并重写perform\u create方法。你知道吗

def perform_create(self, serializer):
    my_policy = serializer.save()
    # you custom calculation for rescue_id
    rescue_obj = Rescue.objects.create(rescue_id='QD1234', policy=my_policy)

这里记录了perform create方法:https://www.django-rest-framework.org/api-guide/generic-views/#methods

相关问题 更多 >