Django REST Framework嵌套序列化器没有任何效果

时间:2016-04-25 02:46:53

标签: python django rest serialization

我正在尝试在Django REST Framework中设置嵌套的序列化程序,但在遵循文档中的简短指南http://www.django-rest-framework.org/api-guide/relations/#nested-relationships后,我在序列化数据中有无变化

models.py

class Franchise(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)


class Item(models.Model):
    id = models.AutoField(primary_key=True)
    franchise = models.ForeignKey(Franchise, on_delete=None)
    title = models.CharField(max_length=255)

初始 serializers.py

class ItemListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = ('id', 'franchise', 'title')


class FranshiseDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = Franchise
        fields = ('id', 'name', 'items')

当我使用查询集查询ItemListSerializer时,我会返回预期

[
    {
        "id": 1,
        "franchise": 1,
        "title": "Item 1",
    },
    {
        "id": 2,
        "franchise": 1,
        "title": "Item 2"
    },
    {
        "id": 3,
        "franchise": 2,
        "title": "Item 3",
    }
]

当我使用预先存在的特许经营对象查询FranchiseDetailSerializer时,预期结果。

{
    "id": 1,
    "name": "Franchise 1"
}

现在,当我按照关于嵌套关系的DRF指南更改FranchiseDetailSerializer时:

class FranshiseDetailSerializer(serializers.ModelSerializer):
    items = ItemListSerializer(many=True, read_only=True)

    class Meta:
        model = Franchise
        fields = ('id', 'name', 'items')

我希望得到以下结果:

{
    "id": 1,
    "name": "Franchise 1"
    "items": [
       {"id": 1, "title": "Item 1", "franchise": 1},
       {"id": 2, "title": "Item 2", "franchise": 1}
    ]
}

但相反,我得到没有变化,好像我根本没有更新FranchiseDetailSerializer

{
    "id": 1,
    "name": "Franchise 1"
}

对我而言最糟糕的部分是我发生任何错误,我只是没有看到结果

感谢任何和所有帮助,谢谢。

1 个答案:

答案 0 :(得分:4)

实际上你错过了一小部分文档:)

  

album = models.ForeignKey(相册,related_name ='tracks')

related_name

中定义ForeignKey
franchise = models.ForeignKey(Franchise, on_delete=None, related_name='items')

之后那些东西开始为我工作了。