我有模型 - 商品、服装和 child 模型,如配饰、外套等:
class Commodity(models.Model):
atribute = models.CharField()
class Clother(models.Model):
commodity = models.ForeignKey(Commodity)
clother_atribute = models.CharField()
class Acessories(models.Model):
clother = models.ForeignKey(Clother)
acessories_atribute = models.CharField()
class Outwear(models.Model):
clother = models.ForeignKey(Clother)
outwear_atribute = models.CharField()
如何序列化父模型商品以调用所有垂直依赖项?我想查询商品 id 并获取所有 Clother 属性和 Acessories 或 Outwear 属性。
最佳答案
如果我理解你的问题,你可以定义ClotherSerializer
。您可以使用depth = 1
在此序列化器中序列化嵌套对象:
class ClotherSerializer(serializers.ModelSerializer):
class Meta:
model = Clother
fields = ('id', 'acessories_set', 'outwear_set')
depth = 1
稍后在您的CommoditySerializer
中,您可以使用ClotherSerializer
来序列化clother及其所有关系:
class CommoditySerializer(serializers.ModelSerializer):
clother_set = ClotherSerializer(many=True)
class Meta:
model = Commodity
fields = ('id', 'clother_set')
关于django - 父模型(包括子模型)的序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50968979/