简体   繁体   English

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

[英]How to manually populate a relational model in Django REST

I'm still new to Django and DRF. 我还是Django和DRF的新手。 I have 2 models (Policy and Rescue) and Rescue is related to Policy by the Foreign Key policy_id. 我有2个模型(Policy and Rescue),Rescue与Foreign Key policy_id的Policy相关。 I have no issue to POST a JSON message and get Policy populated with the request data by CreateView. 我没有问题来发布JSON消息并通过CreateView获取使用请求数据填充的策略。 However, the 2nd model Rescue needs be populated based on some calculations from the JSON data POSTed to the Policy. 但是,需要根据发布到策略的JSON数据中的某些计算来填充第二个模型Rescue。 Rescue cannot be POSTed beforehand. 救援不能事先张贴。 I tried hard but had no clue to do so. 我努力了,但没有任何线索这样做。

Is this something to do with nested serializer or something else? 这与嵌套的序列化器或其他东西有关吗?

I've tried to 我试过了

Can I try this way: inside the class CreateView: 我可以尝试这种方式:在类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)

you can use a generic CreateAPIView and override the perform_create method. 您可以使用通用的CreateAPIView并覆盖perform_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 method is documented here: https://www.django-rest-framework.org/api-guide/generic-views/#methods 这里记录了执行创建方法: https//www.django-rest-framework.org/api-guide/generic-views/#methods

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM