Django rest-framework 关联表内容序列化后的显示
数据库表的关系:
category 与 source 是一对多的关系
下面是代码:
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)
class SourceSerializers(serializers.ModelSerializer):
class Meta:
model = Source
fields = ("id","name","amount")
class CategorySerializers(serializers.ModelSerializer):
source = SourceSerializers(many=True,read_only=True)
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")
class CategoryListView(APIView):
def get(self, request):
category = Category.objects.all()
serializers = CategorySerializers(category, many=True)
return Response(serializers.data)
运行结果:
[
{
"id": 1,
"name": "默认分类",
"amount": "0",
"source": [
{
"id": 34,
"name": "博客园",
"amount": "231"
},
{
"id": 35,
"name": "CSDN",
"amount": "643"
}
]
},
{
"id": 2,
"name": "科技频道",
"amount": "0",
"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")
开发中遇到的问题: