【问题标题】:Serializing specific fields from another model序列化来自另一个模型的特定字段
【发布时间】:2021-04-20 14:04:28
【问题描述】:

我试图从 Policy 模型中序列化 policy_length、coverage_amount 并在使用 Insuree 模型的序列化程序中使用它。

我正在使用保单和被保险人模型:

政策模型

class Policy(TimeStampedModel):

 policy_length = models.FloatField(max_length=2, blank=True, null=True)
 coverage_amount = models.FloatField(max_length=256, blank=True, null=True)

投保人模式

class Insuree(TimeStampedModel):
 user = models.OneToOneField(
    'User', related_name='insuree', null=False, on_delete=models.CASCADE,
    primary_key=True)
 coverage_amount = models.ForeignKey(Policy, on_delete=models.CASCADE, max_length=256, blank=True, null=True)
 policy_length = models.ForeignKey(Policy, on_delete=models.CASCADE, max_length=2, blank=True, null=True)

类 PolicySelectionSerializer(serializers.ModelSerializer):

class Meta:
    model = Insuree
    fields = ('age', 'gender', 'disposable_income') #Current fields

    fields = ('age','gender',disposable_income', 'policy_length', 'coverage_amount') #The field I need and want to do

【问题讨论】:

标签: django django-models django-serializer


【解决方案1】:

您可以使用嵌套序列化器。

 PolicySerializer(ModelSerializer)
    class Meta:
        model = Policy
        fields = ( 'policy_length', 'coverage_amount')


 InsureeSerializer(ModelSerializer)
       class Meta:
          policy = PolicySerializer(many = True)
          model = Insuree
          fields = ('age', 'gender', 'disposable_income', 'policy',) 

【讨论】:

    猜你喜欢
    • 2021-03-27
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    相关资源
    最近更新 更多