django - 父模型(包括子模型)的序列化

标签 django django-models django-rest-framework

我有模型 - 商品、服装和 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/

相关文章:

python - 在 Django 中实现站点地图

javascript - 如何在模板中以 12h 格式渲染 Django Forms.TimeField?

django - 删除 Django ORM 中的重复项——多行

python - 在 Django Rest Framework 中添加特定的方法处理程序 detail_route

python - 如何解决类型错误: RelatedManager object is not iterable

python - 如何将 Pandas Dataframe 写入现有的 Django 模型

django 始终将模型字段输出到 PostgreSQL "character varying(200)"

python - 值错误 : invalid literal for int() with base 10 with django. 设置()

python - verbose_name_plural 在模型中出乎意料?

Django 测试休息框架 : APIRequestFactory vs APIClient