我正在尝试序列化相关表,但是无法管理包含嵌套表的嵌套。比方说我有一个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
中?
答案 0 :(得分:1)
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"]