前言
serializers.Serializer可以对modle模型中的字段序列化,并且必须写create和update两个方法。ModelSerializer可以看成是Serializer的一个升级版,功能更强大,更方便。
实际上ModelSerializer类继承了Serializer类。
ModelSerializer
ModelSerializer
类能够让你自动创建一个具有模型中相应字段的Serializer
类。这个ModelSerialize
r类和常规的Serializer
类一样,不同的是:
- 它根据模型自动生成一组字段。
- 它自动生成序列化器的验证器,比如
unique_together
验证器。 - 它默认简单实现了
.create()
方法和.update()
方法。
比如我们创建的一个模型models.py
# models.py
from django.db import models
# 作者:上海悠悠,QQ交流群:750815713
# Create your models here.
class UserPersonalInfo(models.Model):
'''用户个人信息'''
name = models.CharField(max_length=10, verbose_name="昵称") # 昵称
sex_choices = (
(u'M', u'男'),
(u'F', u'女'),
)
sex = models.CharField(max_length=11,
choices=sex_choices,
verbose_name="性别",
)
age = models.IntegerField(verbose_name="年龄", default="", blank=True)
mail = models.EmailField(max_length=30, default="", blank=True)
create_time = models.DateField(auto_now=True, verbose_name="添加时间")
使用ModelSerializer
序列化后如下
# serializersapi.py
from rest_framework import serializers
from .models import UserPersonalInfo
# 作者:上海悠悠,QQ交流群:750815713
class UserInfoSerializer(serializers.ModelSerializer):
class Meta:
model = UserPersonalInfo
fields = '__all__'
fields
参数设置为'__all__'
会默认序列化所有的字段,可以在django shell交互模式查看
D:softyoyoapi>python manage.py shell
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from apiapp.serializersapi import UserInfoSerializer
>>> serializer = UserInfoSerializer()
>>> print(repr(serializer))
UserInfoSerializer():
id = IntegerField(label='ID', read_only=True)
name = CharField(label='昵称', max_length=10)
sex = ChoiceField(choices=(('M', '男'), ('F', '女')), label='性别')
age = IntegerField(label='年龄', max_value=2147483647, min_value=-2147483648, required=False)
mail = EmailField(allow_blank=True, max_length=30, required=False)
create_time = DateField(label='添加时间', read_only=True)
>>>
fields指定要包括的字段
如果我只想要其中的几个字段,如'id', 'name', 'mail', 'create_time',那么fields参数可以设置成元组类型
# serializersapi.py
from rest_framework import serializers
from .models import UserPersonalInfo
# 作者:上海悠悠,QQ交流群:750815713
class UserInfoSerializer(serializers.ModelSerializer):
class Meta:
model = UserPersonalInfo
fields = ('id', 'name', 'mail', 'create_time')
修改代码后,需exit()
退出shell,再重新进。django shell交互模式运行查看结果
D:softyoyoapi>python manage.py shell
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from apiapp.serializersapi import UserInfoSerializer
>>> serializer = UserInfoSerializer()
>>> print(repr(serializer))
UserInfoSerializer():
id = IntegerField(label='ID', read_only=True)
name = CharField(label='昵称', max_length=10)
mail = EmailField(allow_blank=True, max_length=30, required=False)
create_time = DateField(label='添加时间', read_only=True)
>>>
exclude排除字段列表
与fields
属性设置相反的是,可以用exclude
排除部分字段
# serializersapi.py
from rest_framework import serializers
from .models import UserPersonalInfo
# 作者:上海悠悠,QQ交流群:750815713
class UserInfoSerializer(serializers.ModelSerializer):
class Meta:
model = UserPersonalInfo
# fields = ('id', 'name', 'mail', 'create_time')
exclude = ('id', 'sex', 'age')
django shell交互模式查看结果
# 作者:上海悠悠,QQ交流群:750815713
D:softyoyoapi>python manage.py shell
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from apiapp.serializersapi import UserInfoSerializer
>>> serializer = UserInfoSerializer()
>>> print(repr(serializer))
UserInfoSerializer():
name = CharField(label='昵称', max_length=10)
mail = EmailField(allow_blank=True, max_length=30, required=False)
create_time = DateField(label='添加时间', read_only=True)
>>>
上面例子中用 exclude
参数会排除掉'id', 'sex', 'age'这三个参数。
案例操作
接下来使用serializers.ModelSerializer序列化后(设置fields = 'all'),写个简单的案例,编辑views.py视图,在上一篇基础上,改这一句即可
verify_data = UserInfoSerializer(data=request.data) # 只改这里
# views.py
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import *
from rest_framework.permissions import IsAuthenticated,AllowAny
from .serializersapi import UserInfoSerializer
class UserInfoView(APIView):
'''REST framework的APIView实现获取card列表 # 作者:上海悠悠,QQ交流群:750815713'''
# authentication_classes = (TokenAuthentication,) # token认证
# permission_classes = (IsAuthenticated,) # IsAuthenticated 仅通过认证的用户
permission_classes = (AllowAny,) # 允许所有用户
def get(self, request, format=None):
"""
Return a list of all UserPersonalInfo
"""
info = UserPersonalInfo.objects.all()
serializer = UserInfoSerializer(info, many=True)
return Response(serializer.data)
def post(self, request, format=None):
'''
create UserPersonalInfo
'''
verify_data = UserInfoSerializer(data=request.data) # 只改这里
if verify_data.is_valid():
verify_data.save()
return Response({"message": "create some data!", "data": request.data})
else:
return Response(verify_data.errors)
urls.py设置访问地址
# urls.py
from apiapp import views
from django.conf.urls import url
# 作者:上海悠悠,QQ交流群:750815713
urlpatterns = [
url(r'^info', views.UserPersonalInfoView.as_view()),
]
测试接口
GET请求访问http://127.0.0.1:8000/info
,查询结果
POST请求提交http://127.0.0.1:8000/info
,测试结果