前言serializers.Serializer可以對(duì)modle模型中的字段序列化,并且必須寫create和update兩個(gè)方法,。ModelSerializer可以看成是Serializer的一個(gè)升級(jí)版,,功能更強(qiáng)大,,更方便,。 實(shí)際上ModelSerializer類繼承了Serializer類,。 ModelSerializerModelSerializer 類能夠讓你自動(dòng)創(chuàng)建一個(gè)具有模型中相應(yīng)字段的Serializer 類,。這個(gè)ModelSerialize r類和常規(guī)的Serializer 類一樣,,不同的是:
它根據(jù)模型自動(dòng)生成一組字段。 它自動(dòng)生成序列化器的驗(yàn)證器,,比如unique_together 驗(yàn)證器,。 它默認(rèn)簡(jiǎn)單實(shí)現(xiàn)了.create() 方法和.update() 方法,。
比如我們創(chuàng)建的一個(gè)模型models.py # models.py from django.db import models # 作者:上海悠悠,QQ交流群:750815713
# Create your models here. class UserPersonalInfo(models.Model): '''用戶個(gè)人信息''' 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="添加時(shí)間") 使用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 參數(shù)設(shè)置為'__all__' 會(huì)默認(rèn)序列化所有的字段,,可以在django shell交互模式查看
D:\soft\yoyoapi>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='添加時(shí)間', read_only=True) >>> fields指定要包括的字段如果我只想要其中的幾個(gè)字段,如’id’, 'name’, 'mail’, 'create_time’,,那么fields參數(shù)可以設(shè)置成元組類型 # 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,,再重新進(jìn),。django shell交互模式運(yùn)行查看結(jié)果 D:\soft\yoyoapi>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='添加時(shí)間', read_only=True) >>> exclude排除字段列表與fields 屬性設(shè)置相反的是,可以用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交互模式查看結(jié)果 # 作者:上海悠悠,,QQ交流群:750815713 D:\soft\yoyoapi>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='添加時(shí)間', read_only=True) >>> 上面例子中用 exclude 參數(shù)會(huì)排除掉’id’, 'sex’, 'age’這三個(gè)參數(shù)。 案例操作接下來(lái)使用serializers.ModelSerializer序列化后(設(shè)置fields = 'all'),,寫個(gè)簡(jiǎn)單的案例,,編輯views.py視圖,在上一篇基礎(chǔ)上,改這一句即可 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實(shí)現(xiàn)獲取card列表 # 作者:上海悠悠,,QQ交流群:750815713''' # authentication_classes = (TokenAuthentication,) # token認(rèn)證 # permission_classes = (IsAuthenticated,) # IsAuthenticated 僅通過(guò)認(rèn)證的用戶 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設(shè)置訪問(wèn)地址 # urls.py from apiapp import views from django.conf.urls import url
# 作者:上海悠悠,,QQ交流群:750815713
urlpatterns = [ url(r'^info', views.UserPersonalInfoView.as_view()), ] 測(cè)試接口GET請(qǐng)求訪問(wèn)http://127.0.0.1:8000/info ,查詢結(jié)果 POST請(qǐng)求提交http://127.0.0.1:8000/info ,,測(cè)試結(jié)果 2019第一期《python測(cè)試開發(fā)》課程,,10月13號(hào)開學(xué)!本期上課時(shí)間:10月13號(hào)-12月8號(hào),每周六,、周日晚上20:30-22:30
|