数据库表的关系:
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
Category Model中并没有Source字段。所以这样写不会显示。
可以尝试在CategorySerializer中增加一个自定义字段:
问题解决了,只需要再models.py里面的外键添加一个反向关联的外键名称即可。
添加
related_name="source"
model.py的代码如下: