使用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": []
    }
]

最佳答案

感谢Klaus D的评论,问题得以解决。
我们可以这样在 .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')


如果未在外键中添加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")

09-26 04:22