父模型(包括子模型)的序列化 [英] Serialization of parent model including child models
问题描述
我有一些模型-商品模型,Clother和子模型,例如配饰,外套等:
I have models - Commodity, Clother and child models, as Acessories, Outwear, etc.:
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属性。谢谢!
How can I serialize parent model Commodity to call all vertical dependencies. I suppose to query Commodity id and get all Clother attributes and Acessories or Outwear attributes. Thanks!
推荐答案
如果我了解您的问题,则可以定义 ClotherSerializer
。您可以使用 depth = 1
来序列化此序列化器中的嵌套对象:
If I understood your problem you can define ClotherSerializer
. You can use depth = 1
to serialize nested objects in this serializer:
class ClotherSerializer(serializers.ModelSerializer):
class Meta:
model = Clother
fields = ('id', 'acessories_set', 'outwear_set')
depth = 1
稍后在 CommoditySerializer
中,您可以使用 ClotherSerializer
序列化衣服及其所有关系:
Later in your CommoditySerializer
you can use ClotherSerializer
to serialize clother and all it's relation:
class CommoditySerializer(serializers.ModelSerializer):
clother_set = ClotherSerializer(many=True)
class Meta:
model = Commodity
fields = ('id', 'clother_set')
这篇关于父模型(包括子模型)的序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!