博客五部曲之三 - 博客RESTful
1577 浏览 5 years, 9 months
4 serializer 序列华模型数据
版权声明: 转载请注明出处 http://www.codingsoho.com/序列华模型数据
在http://www.django-rest-framework.org/api-guide/serializers/中描述到
The serializers in REST framework work very similarly to Django's Form and ModelForm classes. We provide a Serializerclass which gives you a powerful, generic way to control the output of your responses, as well as a ModelSerializer class which provides a useful shortcut for creating serializers that deal with model instances and querysets.
所以,序列化类非常类似Form,Serializer它能控制响应的输出内容。ModelSerializer能够快速处理模型实例和查询集。
这一节我们会用ModelSerializer来让ListView工作起来,下一节我们会用Shell来操作Serializer,让我们来更好地理解它怎么实时工作的。
serializer
创建文件posts.api.serializer.py
from rest_framework import serializers
from posts.models import Post
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = [
"title",
"slug",
"content"
]
我们继承自ModelSerializer,跟Form类似,定义了model和fields,fields里显式定义的这些字段将在api 视图中显示出来。
加这个类添加到视图中
from posts.api.serializers import PostSerializer
class PostListAPIView(ListAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
访问 http://127.0.0.1:8000/api/posts/,正常显示了