使用ModelSerializer序列化
编辑blogs目录下的serializers.py
from rest_framework import serializers
from blogs.models import Article
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
# fields = ['id', 'title', 'category', 'brief', 'content', 'click_num', 'cover', 'add_time']
fields = '__all__'
运行项目看到所有字段都展示出来了,但是发现category和user外键显示的是id,希望能把文章对应的类型名称内容、用户名、标签名称都展示出来,在users目录下新建serializers.py
from rest_framework import serializers
from users.models import UserProfile
class UserSimpleSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ['id', 'username', 'nickname', 'avatar']
编辑blogs目录下的serializers.py
from rest_framework import serializers
from .models import Article, BlogCategory, BlogTag
from users.serializers import UserSimpleSerializer
class BlogCategorySerializer(serializers.ModelSerializer):
class Meta:
model = BlogCategory
fields = ['id', 'name']
class BlogTagSerializer(serializers.ModelSerializer):
class Meta:
model = BlogTag
fields = ['id', 'name']
class ArticleSerializer(serializers.ModelSerializer):
category = BlogCategorySerializer()
tags = BlogTagSerializer(many=True)
user = UserSimpleSerializer()
class Meta:
model = Article
# fields = ['id', 'title', 'category', 'brief', 'content', 'click_num', 'cover', 'add_time']
fields = '__all__'
运行项目,此时的category、tags、user的名称都展示出来了
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"id": 1,
"category": {
"id": 3,
"name": "天文地理"
},
"tags": [
{
"id": 1,
"name": "python"
},
{
"id": 2,
"name": "java"
}
],
"user": {
"id": 1,
"username": "admin",
"nickname": "管理员",
"avatar": "/media/users/avatars/0.jpg"
},
"title": "中国父亲,亟待走出“舒适区”",
"brief": "别人当他敌人,他却又当敌人是朋友,他永远坚持自己的信条,但在处理具体事物时,又不乏灵活的手腕。",
"cover": "/media/blogs/articles/covers/2.jpg",
"content": "内容...",
"click_num": 100,
"favor_num": 63,
"comment_num": 97,
"add_time": "2020-01-05T16:23:00"
},
{
...
...
}
...
]
注意点
标签是多对多关系,需要加上many=True,tags = BlogTagSerializer(many=True)
版权声明:如无特殊说明,文章均为本站原创,转载请注明出处
本文链接:http://zhangyanc.club/subject/article/django-modelserializer/
许可协议:署名-非商业性使用 4.0 国际许可协议