DRF,modelSerializer相关的嵌套表

时间:2020-09-17 06:00:37

标签: django django-rest-framework

我正在尝试序列化相关表,但是无法管理包含嵌套表的嵌套。比方说我有一个Project模型。

class Project(models.Model):

  project_name = models.CharField(max_length=255)
  path = models.CharField(max_length=50)

  def __str__(self):
      return self.project_name

该项目模型与Plan模型有很多关系。

class Plan(models.Model):

  project = models.ForeignKey(Project,
    on_delete=models.CASCADE, 
    related_name="plans")
  ...
  ...

  def __str__(self):
    return self.type

一切都很好。直到这里,我仍使用嵌套的Plan模型对项目表进行序列化但是 Plan模型也具有hasMany关系(使用PlanImage模型) / p>

class PlanImage(models.Model):
  plan = models.ForeignKey(Plan, 
    on_delete=models.CASCADE, 
    related_name="plan_images")
  ... 
  ...

因此,如果我这样做,请在我的serializers.py

class ProjectSerializer(serializers.ModelSerializer):
  class Meta:
    model = Project
    fields = ["id", "project_name", "path", "plans"]
    depth = 1

但是项目附带了嵌套的Plan表。在Plan表中,当然没有PlanImage表。我检查了DRF docs,但找不到路。如何将PlanImage包含在Plan中?

1 个答案:

答案 0 :(得分:1)

使用nested serialization技术

class PlanImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = PlanImage
        fields = ['required', 'fields']


class PlanSerializer(serializers.ModelSerializer):
    plan_images = PlanImageSerializer(many=True)

    class Meta:
        model = Plan
        fields = ['id', 'plan_images']


class ProjectSerializer(serializers.ModelSerializer):
    plans = PlanSerializer(many=True)

    class Meta:
        model = Project
        fields = ["id", "project_name", "path", "plans"]