python - Django rest-framework 关联表内容没有显示
高洛峰
高洛峰 2017-04-18 10:12:15
0
2
473

数据库表的关系:
category 与 source 是一对多的关系

select * from reader_category,reader_source where reader_category.id = reader_source.category_id 

查询结果:


下面是代码:

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()
    # 外键
    category = models.ForeignKey(Category)

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")

views.py

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

运行结果:

问题:

在序列化后,代码中已经把source加进来了,为什么结果没有显示source?

我希望的结果是这样的:

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

其他信息:
django版本:1.8.2

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(2)
刘奇

Category Model中并没有Source字段。所以这样写不会显示。

可以尝试在CategorySerializer中增加一个自定义字段:

class CategorySerializers(serializers.ModelSerializer):
    source = serializers.SerializerMethodField()
    
    def get_source(self, obj):
        sources = Source.objects.filter(category=obj)
        return SourceSerializers(sources, many=True, read_only=True).data
        
    class Meta:
        model = Category
        fields = ("id","name","amount","source")
大家讲道理

问题解决了,只需要再models.py里面的外键添加一个反向关联的外键名称即可。
添加related_name="source"

model.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()
    # 外键
    category = models.ForeignKey(Category, related_name="source")
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!