【问题标题】:Django REST, serializing variable/multiple nested OnetoOne relationshipDjango REST,序列化变量/多个嵌套的 OnetoOne 关系
【发布时间】:2019-10-29 21:32:00
【问题描述】:

抱歉,如果标题不清楚问题是什么,我不确定如何描述它。

我有一个“父”调查模型,其中包含所有调查共有的一般字段。

class Survey(models.Model):
    ...

但是,根据调查的类型,需要额外/不同的字段

class SurveyA(models.Model):
    survey = models.OneToOneField(
        Survey,
        on_delete=models.CASCADE,
        primary_key=True
    )
    fieldA = models.TextField()

class SurveyB(models.Model):
    survey = models.OneToOneField(
        Survey,
        on_delete=models.CASCADE,
        primary_key=True
    )
    fieldC = models.TextField()

class SurveyN(models.Model):
    survey = models.OneToOneField(
        Survey,
        on_delete=models.CASCADE,
        primary_key=True
    )
    fieldN = models.TextField()

当我将“调查”对象序列化为 json 时,我希望相应的 SurveryA、B..N 对象与它一起序列化,无论在 OnetoOneField 中与哪种类型的子调查相关。这是可行的吗?

序列化所有Survey 模型时的预期输出:

[
    {
        "id": 1,
        "SurveyA": {
            "fieldA": "this is an 'A' type Survey",
        }
    },
    {
        "id": 2,
        "SurveyB": {
            "fieldB": "this is an 'B' type Survey",
        }
    },
    {
        "id": 3,
        "SurveyN": {
            "fieldN": "this is an 'N' type Survey",
        }
    }
]

【问题讨论】:

    标签: python django django-models django-rest-framework django-serializer


    【解决方案1】:

    使用SerializeMethodField 找到了解决方案,如果有人有任何其他建议,将不胜感激。

    来自Django Rest Framework Conditional Field on Serializer的想法

    class SurveySerializer(serializers.HyperlinkedModelSerializer):
        survey_type = serializers.SerializerMethodField()
        class Meta:
            model = Survey
            fields = '__all__'
    
        def get_survey_type(self, obj):
            if SurveyA.objects.filter(pk=obj.pk).exists():
                survey_type = SurveyASerializer(SurveyA.objects.get(pk=obj.pk), context=self.context)
            elif SurveyB.objects.filter(pk=obj.pk).exists():
                survey_type = SurveyBSerializer(SurveyB.objects.get(pk=obj.pk), context=self.context)
            elif SurveyN.objects.filter(pk=obj.pk).exists():
                survey_type = SurveyNSerializer(SurveyN.objects.get(pk=obj.pk), context=self.context)
            return survey_type.data
    

    注意:context=self.context 必须传递,因为我正在使用超链接模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-30
      • 1970-01-01
      • 2017-03-12
      • 2017-02-21
      • 2017-02-09
      • 2018-02-17
      • 2015-03-04
      • 2020-04-23
      相关资源
      最近更新 更多