django rest-farmework嵌套关系

时间:2017-01-07 11:50:45

标签: python django django-rest-framework

使用django rest-farmework来实现API,这里的嵌套关系存在问题。无法显示与外键关联的内容,具体代码如下:

models.py

class Category(models.Model):
    name = models.CharField(max_length=30)
    amount = models.IntegerField()

class Source(models.Model):
    name = models.CharField(max_length=50)
    rss_link = models.URLField()
    amount = models.IntegerField()
    # ForeignKey
    category = models.ForeignKey(Category)

views.py

class CategoryListView(APIView):
    def get(self, request):
        category = Category.objects.all()
        serializers = CategorySerializers(category, many=True)
        return Response(serializers.data)

serializers.py

class SourceSerializers(serializers.ModelSerializer):
    class Meta:
        model = Source
        fields = ("id","name","amount")

class CategorySerializers(serializers.ModelSerializer):
    source = SourceSerializers(many=True, read_only=True)

    class Meta:
        model = Category
        fields = ("id","name","amount","source")

程序运行结果:

[
    {
        "id": 1,
        "name": "默认分类",
        "amount": 0
    },
    {
        "id": 2,
        "name": "科技频道",
        "amount": 0
    }
]

为什么不能在结果中显示'来源'?

我希望结果是这样的

[
    {
        "id": 1,
        "name": "默认分类",
        "amount": "0",
        "source": [
            {
                "id": 34,
                "name": "博客园",
                "amount": "231"
            },
            {
                "id": 35,
                "name": "CSDN",
                "amount": "643"
            }
        ]
    },
    {
        "id": 2,
        "name": "科技频道",
        "amount": "0",
        "source": []
    }
]

1 个答案:

答案 0 :(得分:3)

感谢Klaus D的评论,问题解决了。 我们可以在models.py中添加related_name = 'source',如下所示:

class Source(models.Model):
    name = models.CharField(max_length=50)
    rss_link = models.URLField()
    amount = models.IntegerField()
    # ForeignKey
    category = models.ForeignKey(Category,related_name = 'source')

如果未在foreignkey中添加related_name,则默认为“source_set”。

所以,我们也可以解决这个问题:

#serializers.py
class CategorySerializers(serializers.ModelSerializer):
    source_set = SourceSerializers(many=True, read_only=True)

    class Meta:
        model = Category
        fields = ("id","name","amount","source_set")