- 解析模块
- 异常处理模块
- 响应模块
- 序列化组件
- Serializer
- ModelSerializer
-曾老湿, 江湖人称曾老大。
-多年互联网运维工作经验,曾负责过大规模集群架构自动化运维管理工作。 -擅长Web集群架构与自动化运维,曾负责国内某大型金融公司运维工作。 -devops项目经理兼DBA。 -开发过一套自动化运维平台(功能如下): 1)整合了各个公有云API,自主创建云主机。 2)ELK自动化收集日志功能。 3)Saltstack自动化运维统一配置管理工具。 4)Git、Jenkins自动化代码上线及自动化测试平台。 5)堡垒机,连接Linux、Windows平台及日志审计。 6)SQL执行及审批流程。 7)慢查询日志分析web界面。
解析模块
为啥要配置解析模块 |
---|
"""
1)drf给我们通过了多种解析数据包方式的解析类
2)我们可以通过配置来控制前台提交的哪些格式的数据后台在解析,哪些数据不解析
3)全局配置就是针对每一个视图类,局部配置就是针对指定的视图来,让它们可以按照配置规则选择性解析数据
"""
代码语言:javascript复制from rest_framework.views import APIView
from rest_framework.response import Response
class Book(APIView):
def get(self, request, *args, **kwargs):
return Response('get OK')
def post(self, request, *args, **kwargs):
## url拼接参数:只有一种传参方式就是拼接参数
print(request.query_params)
## 数据包参数:有三种传参方式,form-data、urlencoded、json
print(request.data)
return Response('post OK')
源码入口 |
---|
# APIView类的dispatch方法中
request = self.initialize_request(request, *args, **kwargs) # 点进去
# 获取解析类
parsers=self.get_parsers(), # 点进去
# 去类属性(局部配置) 或 配置文件(全局配置) 拿 parser_classes
return [parser() for parser in self.parser_classes]
全局配置 |
---|
项目settings.py文件
代码语言:javascript复制REST_FRAMEWORK = {
# 全局解析类配置
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser', # json数据包
'rest_framework.parsers.FormParser', # urlencoding数据包
'rest_framework.parsers.MultiPartParser' # form-date数据包
],
}
局部配置 |
---|
应用views.py的具体视图类
代码语言:javascript复制from rest_framework.parsers import JSONParser
class Book(APIView):
# 局部解析类配置,只要json类型的数据包才能被解析
parser_classes = [JSONParser]
pass
异常处理模块
为啥要定义异常模块 |
---|
"""
1)所有经过drf的APIView视图类产生的异常,都可以提供异常处理方案
2)drf默认提供了异常处理方案(rest_framework.views.exception_handler),但是处理范围有限
3)drf提供的处理方案两种,处理了返回异常现象,没处理返回None(后续就是服务器抛异常给前台)
4)自定义异常的目的就是解决drf没有处理的异常,让前台得到合理的异常信息返回,后台记录异常具体信息
"""
源码分析 |
---|
# 异常模块:APIView类的dispatch方法中
response = self.handle_exception(exc) # 点进去
# 获取处理异常的句柄(方法)
# 一层层看源码,走的是配置文件,拿到的是rest_framework.views的exception_handler
# 自定义:直接写exception_handler函数,在自己的配置文件配置EXCEPTION_HANDLER指向自己的
exception_handler = self.get_exception_handler()
# 异常处理的结果
# 自定义异常就是提供exception_handler异常处理函数,处理的目的就是让response一定有值
response = exception_handler(exc, context)
如何使用 |
---|
自定义exception_handler函数如何书写实现体
代码语言:javascript复制# 修改自己的配置文件setting.py
REST_FRAMEWORK = {
# 全局配置异常模块
'EXCEPTION_HANDLER': 'api.exception.exception_handler',
}
代码语言:javascript复制# 1)先将异常处理交给rest_framework.views的exception_handler去处理
# 2)判断处理的结果(返回值)response,有值代表drf已经处理了,None代表需要自己处理
# 自定义异常处理文件exception,在文件中书写exception_handler函数
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework.views import Response
from rest_framework import status
def exception_handler(exc, context):
# drf的exception_handler做基础处理
response = drf_exception_handler(exc, context)
# 为空,自定义二次处理
if response is None:
# print(exc)
# print(context)
print('%s - %s - %s' % (context['view'], context['request'].method, exc))
return Response({
'detail': '服务器错误'
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True)
return response
响应模块
响应类型构造器 |
---|
rest_framework.response.Response
代码语言:javascript复制def __init__(self, data=None, status=None,
template_name=None, headers=None,
exception=False, content_type=None):
"""
:param data: 响应数据
:param status: http响应状态码
:param template_name: drf也可以渲染页面,渲染的页面模板地址(不用了解)
:param headers: 响应头
:param exception: 是否异常了
:param content_type: 响应的数据格式(一般不用处理,响应头中带了,且默认是json)
"""
pass
使用 |
---|
常规实例化响应对象
代码语言:javascript复制# status就是解释一堆 数字 网络状态码的模块
from rest_framework import status就是解释一堆 数字 网络状态码的模块
# 一般情况下只需要返回数据,status和headers都有默认值
return Response(data={数据}, status=status.HTTP_200_OK, headers={设置的响应头})
序列化组件
序列化组件介绍 |
---|
1.Serializer(偏底层) 2.ModelSerializer(重点) 3.ListModelSerializer(辅助群改)
Serializer
模型层 |
---|
from django.db import models
# Create your models here.
class User(models.Model):
GENDER_CHOICES = [
[0, '男'],
[1, '女'],
]
name = models.CharField(max_length=64)
pwd = models.CharField(max_length=32)
phone = models.CharField(max_length=11,null=True,default=None)
gender = models.IntegerField(choices=GENDER_CHOICES, default=0)
icon = models.ImageField(upload_to='icon',default='icon/default.jpg')
class Meta:
db_table = 'zls_user'
verbose_name = '用户'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
admin注册 |
---|
from django.contrib import admin
from . import models
# Register your models here.
admin.site.register(models.User)
数据库迁移 |
---|
MacBook-pro:rest_ful driverzeng$ python3 manage.py makemigrations
MacBook-pro:rest_ful driverzeng$ python3 manage.py migrate
settings配置 |
---|
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
图片urls配置 |
---|
一定要放在主路由中
代码语言:javascript复制from django.conf.urls import url,include
from django.contrib import admin
from django.views.static import serve
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include('api.urls')),
url(r'^media/(?P<path>.*)', serve,{'document_root': settings.MEDIA_ROOT}),
]
使用admin创建用户 |
---|

路由 |
---|
from django.conf.urls import url
from . import views
from django.views.static import serve
from django.conf import settings
urlpatterns = [
url(r'^users/$', views.User.as_view()),
url(r'^users/(?P<pk>.*)/$', views.User.as_view()),
]
serializer |
---|
定义序列化的字段,有点类似于Forms组件的用法。
需要先创建一个serializer.py文件,当然文件名可以自定义,与models文件在同一级即可
代码语言:javascript复制# 序列化组件,为每一个model类,提供一套序列化工具类
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
name = serializers.CharField()
phone = serializers.CharField()
gender = serializers.IntegerField()
icon = serializers.ImageField()
视图 |
---|
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models
from . import serializers
class User(APIView):
def get(self,request,*args,**kwargs):
pk = kwargs.get('pk')
if pk:
try:
user_obj = models.User.objects.get(pk=pk)
## 用户对象不能直接作为数据返回给前台
## 序列化
user_ser = serializers.UserSerializer(user_obj)
return Response({
'status':0,
'msg': 0,
'results':user_ser.data
})
except:
return Response({
'status': 2,
'msg': '用户不存在',
})
else:
user_obj_list = models.User.objects.all()
# 序列化多个数据
user_ser_data = serializers.UserSerializer(user_obj_list,many=True).data
return Response({
'status':0,
'msg':0,
'results':user_ser_data
})

自定义序列化属性 |
---|
gender是0和1,看起来很别扭。
代码语言:javascript复制# 序列化组件,为每一个model类,提供一套序列化工具类
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
name = serializers.CharField()
phone = serializers.CharField()
gender = serializers.IntegerField()
icon = serializers.ImageField()
## 自定义序列化属性
gender_value = serializers.SerializerMethodField()
def get_gender_value(self,obj):
return obj.get_gender_display()

在序列化过程中,我们可以删除不想显示的字段,就比如说是gender,这样的话,就可以把gender_value
改成gender
了
# 序列化组件,为每一个model类,提供一套序列化工具类
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
name = serializers.CharField()
phone = serializers.CharField()
# gender = serializers.IntegerField()
icon = serializers.ImageField()
## 自定义序列化属性
gender = serializers.SerializerMethodField()
def get_gender(self, obj):
return obj.get_gender_display()

icon传递过去的数据,在前台发现点击无法直接看到图片,所以我们可以修改属性,传递一个完整路径
代码语言:javascript复制# 序列化组件,为每一个model类,提供一套序列化工具类
from rest_framework import serializers
from django.conf import settings
class UserSerializer(serializers.Serializer):
name = serializers.CharField()
phone = serializers.CharField()
# gender = serializers.IntegerField()
# icon = serializers.ImageField()
## 自定义序列化属性
gender = serializers.SerializerMethodField()
def get_gender(self, obj):
return obj.get_gender_display()
icon = serializers.SerializerMethodField()
def get_icon(self, obj):
return '%s%s%s' % (r'http://127.0.0.1:8000', settings.MEDIA_URL, str(obj.icon))

反序列化 |
---|
# 序列化组件,为每一个model类,提供一套序列化工具类
from rest_framework import serializers
from django.conf import settings
class UserDescSerializer(serializers.Serializer):
### 1.哪些字段必须反序列化?
### 2.字段都有哪些安全校验?
### 3.哪些字段需要额外提供校验?
### 4.哪些字段间存在联合校验?
#### 注意:反序列化字段,都是入库字段,不会出现自定义属性
name = serializers.CharField()
pwd = serializers.CharField()
phone = serializers.CharField()
gender = serializers.IntegerField()
代码语言:javascript复制from rest_framework.views import APIView
from rest_framework.response import Response
from . import models
from . import serializers
class User(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
try:
user_obj = models.User.objects.get(pk=pk)
## 用户对象不能直接作为数据返回给前台
## 序列化
user_ser = serializers.UserSerializer(user_obj)
return Response({
'status': 0,
'msg': 0,
'results': user_ser.data
})
except:
return Response({
'status': 2,
'msg': '用户不存在',
})
else:
user_obj_list = models.User.objects.all()
# 序列化多个数据
user_ser_data = serializers.UserSerializer(user_obj_list, many=True).data
return Response({
'status': 0,
'msg': 0,
'results': user_ser_data
})
# 暂时只考虑单增
def post(self, request, *args, **kwargs):
request_data = request.data
## 数据是否合法
if not isinstance(request_data, dict) or request_data == {}:
return Response({
'status': 1,
'msg': '数据有误',
})
book_ser = serializers.UserDescSerializer(request_data)
return Response({
'status': 0,
'msg': 'OK',
})

代码语言:javascript复制from rest_framework.views import APIView
from rest_framework.response import Response
from . import models
from . import serializers
class User(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
try:
user_obj = models.User.objects.get(pk=pk)
## 用户对象不能直接作为数据返回给前台
## 序列化
user_ser = serializers.UserSerializer(user_obj)
return Response({
'status': 0,
'msg': 0,
'results': user_ser.data
})
except:
return Response({
'status': 2,
'msg': '用户不存在',
})
else:
user_obj_list = models.User.objects.all()
# 序列化多个数据
user_ser_data = serializers.UserSerializer(user_obj_list, many=True).data
return Response({
'status': 0,
'msg': 0,
'results': user_ser_data
})
# 暂时只考虑单增
def post(self, request, *args, **kwargs):
request_data = request.data
## 数据是否合法
if not isinstance(request_data, dict) or request_data == {}:
return Response({
'status': 1,
'msg': '数据有误',
})
book_ser = serializers.UserDescSerializer(data=request_data)
if book_ser.is_valid():
## 校验通过,完成新增
book_obj = book_ser.save()
return Response({
'status': 0,
'msg': 'OK',
'results': serializers.UserSerializer(book_obj).data
})
else:
## 校验失败
return Response({
'status': 1,
'msg': book_ser.errors,
})
通过,并进入校验阶段

反序列化校验与入库 |
---|
serializer.py
代码语言:javascript复制# 序列化组件 - 为每一个model类通过一套序列化工具类
# 序列化组件的工作方式与django froms组件非常相似
from rest_framework import serializers, exceptions
from django.conf import settings
from . import models
class UserSerializer(serializers.Serializer):
name = serializers.CharField()
phone = serializers.CharField()
# 序列化提供给前台的字段个数由后台决定,可以少提供,
# 但是提供的数据库对应的字段,名字一定要与数据库字段相同
# sex = serializers.IntegerField()
# icon = serializers.ImageField()
# 自定义序列化属性
# 属性名随意,值由固定的命名规范方法提供:
# get_属性名(self, 参与序列化的model对象)
# 返回值就是自定义序列化属性的值
gender = serializers.SerializerMethodField()
def get_gender(self, obj):
# choice类型的解释型值 get_字段_display() 来访问
return obj.get_gender_display()
icon = serializers.SerializerMethodField()
def get_icon(self, obj):
# settings.MEDIA_URL: 自己配置的 /media/,给后面高级序列化与视图类准备的
# obj.icon不能直接作为数据返回,因为内容虽然是字符串,但是类型是ImageFieldFile类型
return '%s%s%s' % (r'http://127.0.0.1:8000', settings.MEDIA_URL, str(obj.icon))
class UserDeserializer(serializers.Serializer):
# 1) 哪些自动必须反序列化
# 2) 字段都有哪些安全校验
# 3) 哪些字段需要额外提供校验
# 4) 哪些字段间存在联合校验
# 注:反序列化字段都是用来入库的,不会出现自定义方法属性,会出现可以设置校验规则的自定义属性(re_pwd)
name = serializers.CharField(
max_length=64,
min_length=3,
error_messages={
'max_length': '太长',
'min_length': '太短'
}
)
pwd = serializers.CharField()
phone = serializers.CharField(required=False)
sex = serializers.IntegerField(required=False)
# 自定义有校验规则的反序列化字段
re_pwd = serializers.CharField(required=True)
# 小结:
# name,pwd,re_pwd为必填字段
# phone,sex为选填字段
# 五个字段都必须提供完成的校验规则
# 局部钩子:validate_要校验的字段名(self, 当前要校验字段的值)
# 校验规则:校验通过返回原值,校验失败,抛出异常
def validate_name(self, value):
if 'g' in value.lower(): # 名字中不能出现g
raise exceptions.ValidationError('名字非法,是个鸡贼!')
return value
# 全局钩子:validate(self, 系统与局部钩子校验通过的所有数据)
# 校验规则:校验通过返回原值,校验失败,抛出异常
def validate(self, attrs):
pwd = attrs.get('pwd')
re_pwd = attrs.pop('re_pwd')
if pwd != re_pwd:
raise exceptions.ValidationError({'pwd&re_pwd': '两次密码不一致'})
return attrs
# 要完成新增,需要自己重写 create 方法
def create(self, validated_data):
# 尽量在所有校验规则完毕之后,数据可以直接入库
return models.User.objects.create(**validated_data)
views.py
代码语言:javascript复制from rest_framework.views import APIView
from rest_framework.response import Response
from . import models
from . import serializers
class User(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
try:
user_obj = models.User.objects.get(pk=pk)
## 用户对象不能直接作为数据返回给前台
## 序列化
user_ser = serializers.UserSerializer(user_obj)
return Response({
'status': 0,
'msg': 0,
'results': user_ser.data
})
except:
return Response({
'status': 2,
'msg': '用户不存在',
})
else:
user_obj_list = models.User.objects.all()
# 序列化多个数据
user_ser_data = serializers.UserSerializer(user_obj_list, many=True).data
return Response({
'status': 0,
'msg': 0,
'results': user_ser_data
})
# 暂时只考虑单增
def post(self, request, *args, **kwargs):
request_data = request.data
## 数据是否合法
if not isinstance(request_data, dict) or request_data == {}:
return Response({
'status': 1,
'msg': '数据有误',
})
book_ser = serializers.UserDeserializer(data=request_data)
if book_ser.is_valid():
## 校验通过,完成新增
book_obj = book_ser.save()
print(serializers.UserSerializer(book_obj).data)
return Response({
'status': 0,
'msg': 'OK',
'results': serializers.UserSerializer(book_obj).data
})
else:
## 校验失败
return Response({
'status': 1,
'msg': book_ser.errors
})


总结 |
---|
# 反序列化总结
# 1)book_ser = serializers.UserDeserializer(data=request_data) # 数据必须赋值data
# 2)book_ser.is_valid() # 结果为 通过 | 不通过
# 3)不通过返回 book_ser.errors 给前台,通过 book_ser.save() 得到新增的对象,再正常返回
# 序列化类总结:
# 1)设置必填与选填序列化字段,设置校验规则
# # 2)为需要额外校验的字段提供局部钩子函数,如果该字段不入库,且不参与全局钩子校验,可以将值取出校验
# # 3)为有联合关系的字段们提供全局钩子函数,如果某些字段不入库,可以将值取出校验
# # 4)重写create方法,完成校验通过的数据入库工作,得到新增的对象
"""
1、解析模块:全局局部配置
REST_FRAMEWORK = {
# 全局解析类配置
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
],
}
form rest_framework.parsers import JSONParser, FormParser
class User(APIView):
parser_classes = [JSONParser, FormParser]
def get():
pass
2、异常模块
REST_FRAMEWORK = {
# 全局配置异常模块
'EXCEPTION_HANDLER': 'api.exception.exception_handler',
}
def exception_handler(exc, context):
response = drf views 中的 exception_handler 先处理
if response is None:
通过context,exc记录详细的异常信息
自己自定义响应对象
return Response({
'detail': '服务器错误'
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True)
return response
3、响应模块
Response(data, status, headers, content_type, exception)
4、Serializer序列化模块
序列化
ser:
1)设置需要返回给前台 那些model类有对应的 字段,不需要返回的就不用设置了
2)设置方法字段,字段名可以随意,字段值有 get_字段名 提供,来完成一些需要处理在返回的数据
view:
1)从数据库中将要序列化给前台的model对象,或是对个model对象查询出来
user_obj = models.User.objects.get(pk=pk) 或者
user_obj_list = models.User.objects.all()
2)将对象交给序列化处理,产生序列化对象,如果序列化的是多个数据,要设置many=True
user_ser = serializers.UserSerializer(user_obj) 或者
user_ser = serializers.UserSerializer(user_obj_list, many=True)
3)序列化 对象.data 就是可以返回给前台的序列化数据
return Response({
'status': 0,
'msg': 0,
'results': user_ser.data
})
反序列化
ser:
1)设置必填与选填序列化字段,设置校验规则
2)为需要额外校验的字段提供局部钩子函数,如果该字段不入库,且不参与全局钩子校验,可以将值取出校验
3)为有联合关系的字段们提供全局钩子函数,如果某些字段不入库,可以将值取出校验
4)重写create方法,完成校验通过的数据入库工作,得到新增的对象
view:
"""
ModelSerializer
该方法是重点,完全可以代替Serializer
新建一个项目,基础环境准备
设置数据库 |
---|
mysql> create database drf;
代码语言:javascript复制DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'drf',
"HOST":'10.0.0.51',
"USER":'zls',
"PASSWORD":'123',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
init中设置使用pymysql |
---|
import pymysql
pymysql.install_as_MySQLdb()
drf配置 |
---|
REST_FRAMEWORK = {}
media配置 |
---|
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
时区及语言设置 |
---|
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False
注册drf |
---|
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api.apps.ApiConfig',
'rest_framework'
]
路由分发 |
---|
from django.conf.urls import url,include
from django.contrib import admin
from django.views.static import serve
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include('api.urls')),
url(r'^media/(?P<path>.*)', serve,{'document_root':settings.MEDIA_ROOT}),
]
添加异常模块 |
---|
可有可无
代码语言:javascript复制from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework.response import Response
from rest_framework import status
def exception_handler(exc, context):
# drf的exception_handler做基础处理
response = drf_exception_handler(exc, context)
# 为空,自定义二次处理
if response is None:
# print(exc)
# print(context)
print('%s - %s - %s' % (context['view'], context['request'].method, exc))
return Response({
'detail': '服务器错误'
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True)
return response
全局配置异常模块 |
---|
REST_FRAMEWORK = {
# 全局配置异常模块
'EXCEPTION_HANDLER': 'api.exception.exception_handler',
}
创建表模型 |
---|
from django.db import models
## 图书管理系统:Book、Author、AuthorDetail、Publish
"""
Book表: name、price、img、authors、publish、is_delete、create_time
Publish表: name、address、is_delete、create_time
Author表: name、age、is_delete、create_time
AuthorDetail表: mobile, author、is_delete、create_time
"""
# 1)基表:封装公有字段
class BaseModel(models.Model):
is_delete = models.BooleanField(default=0)
create_time = models.DateTimeField(auto_now_add=True)
## 作为基表,所以这张表不需要创建,需要指定abstract = True
class Meta:
abstract = True
class Book(BaseModel):
# Book表: name、price、img、authors、publish、is_delete、create_time
name = models.CharField(max_length=64)
price = models.DecimalField(max_digits=5, decimal_places=2)
img = models.ImageField(upload_to='img', default='img/default.jpg')
publish = models.ForeignKey(to='Publish')
authors = models.ManyToManyField(to='Author')
class Meta:
db_table = 'book'
verbose_name = '书籍'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class Publish(BaseModel):
# Publish表: name、address、is_delete、create_time
name = models.CharField(max_length=64)
address = models.CharField(max_length=64)
class Meta:
db_table = 'publish'
verbose_name = '出版社'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class Author(BaseModel):
# Author表: name、age、is_delete、create_time
name = models.CharField(max_length=64)
age = models.SmallIntegerField()
class Meta:
db_table = 'author'
verbose_name = '作者'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class AuthorDetail(BaseModel):
# AuthorDetail表: mobile, author、is_delete、create_time
mobile = models.CharField(max_length=11)
author = models.OneToOneField(to='Author')
class Meta:
db_table = 'author_detail'
verbose_name = '作者详情'
verbose_name_plural = verbose_name
def __str__(self):
return '%s的详情' % self.author.name
数据库迁移 |
---|
MacBook-pro:model_ser driverzeng$ python3 manage.py makemigrations
MacBook-pro:model_ser driverzeng$ python3 manage.py migrate

注册admin |
---|
from django.contrib import admin
from . import models
# Register your models here.
admin.site.register(models.Author)
admin.site.register(models.Publish)
admin.site.register(models.AuthorDetail)
admin.site.register(models.Book)
创建超级用户 |
---|
MacBook-pro:model_ser driverzeng$ python3 manage.py createsuperuser
Username (leave blank to use 'driverzeng'): admin
Email address:
Password: admin123
Password (again): admin123
Superuser created successfully.
多表断关联 |
---|
from django.db import models
## 图书管理系统:Book、Author、AuthorDetail、Publish
"""
Book表: name、price、img、authors、publish、is_delete、create_time
Publish表: name、address、is_delete、create_time
Author表: name、age、is_delete、create_time
AuthorDetail表: mobile, author、is_delete、create_time
"""
# 1)基表:封装公有字段
class BaseModel(models.Model):
is_delete = models.BooleanField(default=0)
create_time = models.DateTimeField(auto_now_add=True)
## 作为基表,所以这张表不需要创建,需要指定abstract = True
class Meta:
abstract = True
class Book(BaseModel):
# Book表: name、price、img、authors、publish、is_delete、create_time
name = models.CharField(max_length=64)
price = models.DecimalField(max_digits=5, decimal_places=2)
img = models.ImageField(upload_to='img', default='img/default.jpg')
publish = models.ForeignKey(to='Publish', db_constraint=False, related_name='books', on_delete=models.DO_NOTHING)
authors = models.ManyToManyField(to='Author', db_constraint=False, related_name='books')
class Meta:
db_table = 'book'
verbose_name = '书籍'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class Publish(BaseModel):
# Publish表: name、address、is_delete、create_time
name = models.CharField(max_length=64)
address = models.CharField(max_length=64)
class Meta:
db_table = 'publish'
verbose_name = '出版社'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class Author(BaseModel):
# Author表: name、age、is_delete、create_time
name = models.CharField(max_length=64)
age = models.SmallIntegerField()
class Meta:
db_table = 'author'
verbose_name = '作者'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class AuthorDetail(BaseModel):
# AuthorDetail表: mobile, author、is_delete、create_time
mobile = models.CharField(max_length=11)
### db_constraint=False 不关联
### on_delete=models.CASCADE是级联关系,删除作者同时删除详情
### related_name='detail'反向查询直接使用detail
author = models.OneToOneField(to='Author', db_constraint=False, on_delete=models.CASCADE, related_name='detail')
class Meta:
db_table = 'author_detail'
verbose_name = '作者详情'
verbose_name_plural = verbose_name
def __str__(self):
return '%s的详情' % self.author.name
总结:
1.db_constraint=False 不关联
2.on_delete
代码语言:javascript复制on_delete:
- models.CASCADE 级联,作者删除,详情殉情
- models.SET_NULL 置空,作者删除,详情置空
- models.SET_DEFAULT 重置,作者删除,详情重置
- models.DO_NOTHING 不动,作者删除,详情不动
3.related_name='detail'反向查询直接使用detail
4.多对多,manytomany 不能设置on_delete
admin造数据 |
---|




接口路由 |
---|
子路由
代码语言:javascript复制from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^books/$',views.Book.as_view()),
url(r'^books/(?P<pk>.*)/$',views.Book.as_view()),
]
接口视图 |
---|
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models,serializers
class Book(APIView):
def get(self,request,*args,**kwargs):
pk = kwargs.get('pk')
if pk:
try:
book_obj = models.Book.objects.get(pk=pk)
book_data = serializers.BookModelSerializer(book_obj).data
except:
return Response({
'status':1,
'msg':'书籍不存在'
})
else:
book_query = models.Book.objects.all()
book_data = serializers.BookModelSerializer(book_query,many=True).data
return Response({
'status': 0,
'msg': '成功',
'results': book_data
})
接口序列化文件 |
---|
from rest_framework.serializers import ModelSerializer
from . import models
class BookModelSerializer(ModelSerializer):
class Meta:
## 序列化类,关联的model类
model = models.Book
## 参与序列化的字段
fields = ('name', 'price')

显示所有字段
代码语言:javascript复制from rest_framework.serializers import ModelSerializer
from . import models
class BookModelSerializer(ModelSerializer):
class Meta:
## 序列化类,关联的model类
model = models.Book
## 参与序列化的字段
# fields = ('name', 'price')
fields = '__all__'

排除字段
代码语言:javascript复制from rest_framework.serializers import ModelSerializer
from . import models
class BookModelSerializer(ModelSerializer):
class Meta:
## 序列化类,关联的model类
model = models.Book
## 参与序列化的字段
# fields = ('name', 'price')
## 所有字段
# fields = '__all__'
## 排除字段
exclude = ('id','is_delete','create_time')

自动深度
代码语言:javascript复制from rest_framework.serializers import ModelSerializer
from . import models
class BookModelSerializer(ModelSerializer):
class Meta:
## 序列化类,关联的model类
model = models.Book
## 参与序列化的字段
# fields = ('name', 'price')
## 所有字段
# fields = '__all__'
## 排除字段
exclude = ('id','is_delete','create_time')
## 自动深度
depth = 1

自定义连表字段 |
---|
from django.db import models
## 图书管理系统:Book、Author、AuthorDetail、Publish
"""
Book表: name、price、img、authors、publish、is_delete、create_time
Publish表: name、address、is_delete、create_time
Author表: name、age、is_delete、create_time
AuthorDetail表: mobile, author、is_delete、create_time
"""
# 1)基表:封装公有字段
class BaseModel(models.Model):
is_delete = models.BooleanField(default=0)
create_time = models.DateTimeField(auto_now_add=True)
## 作为基表,所以这张表不需要创建,需要指定abstract = True
class Meta:
abstract = True
class Book(BaseModel):
# Book表: name、price、img、authors、publish、is_delete、create_time
name = models.CharField(max_length=64)
price = models.DecimalField(max_digits=5, decimal_places=2)
img = models.ImageField(upload_to='img', default='img/default.jpg')
publish = models.ForeignKey(to='Publish', db_constraint=False, related_name='books', on_delete=models.DO_NOTHING)
authors = models.ManyToManyField(to='Author', db_constraint=False, related_name='books')
@property
def publish_name(self):
return self.publish.name
代码语言:javascript复制from rest_framework.serializers import ModelSerializer
from . import models
class BookModelSerializer(ModelSerializer):
class Meta:
## 序列化类,关联的model类
model = models.Book
## 参与序列化的字段
fields = ('name', 'price','publish_name')

多表反序列化 |
---|
from rest_framework.serializers import ModelSerializer
from . import models
class BookModelSerializer(ModelSerializer):
class Meta:
## 序列化类,关联的model类
model = models.Book
## 参与序列化的字段
fields = ('name', 'price','img', 'publish_name')
## 所有字段
# fields = '__all__'
## 排除字段
# exclude = ('id','is_delete','create_time')
## 自动深度
# depth = 1
class BookModelDeserializer(ModelSerializer):
class Meta:
## 序列化类,关联的model类
model = models.Book
## 参与序列化的字段
fields = ('name', 'price','img', 'publish', 'authors')
代码语言:javascript复制from rest_framework.views import APIView
from rest_framework.response import Response
from . import models, serializers
class Book(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
try:
book_obj = models.Book.objects.get(pk=pk)
book_data = serializers.BookModelSerializer(book_obj).data
except:
return Response({
'status': 1,
'msg': '书籍不存在'
})
else:
book_query = models.Book.objects.all()
book_data = serializers.BookModelSerializer(book_query, many=True).data
return Response({
'status': 0,
'msg': '成功',
'results': book_data
})
def post(self, request, *args, **kwargs):
request_data = request.data
# if isinstance(request_data,dict):
book_ser = serializers.BookModelDeserializer(data=request_data)
## 当校验失败,马上终止当前视图方法,抛异常返回给前台
book_ser.is_valid(raise_exception=True)
book_obj = book_ser.save()
return Response({
'status': 0,
'msg': '成功',
'results': serializers.BookModelSerializer(book_obj).data
})
校验规则
代码语言:javascript复制from rest_framework.serializers import ModelSerializer
from . import models
class BookModelSerializer(ModelSerializer):
class Meta:
## 序列化类,关联的model类
model = models.Book
## 参与序列化的字段
fields = ('name', 'price', 'img', 'publish_name')
## 所有字段
# fields = '__all__'
## 排除字段
# exclude = ('id','is_delete','create_time')
## 自动深度
# depth = 1
class BookModelDeserializer(ModelSerializer):
class Meta:
## 序列化类,关联的model类
model = models.Book
## 参与序列化的字段
fields = ('name', 'price', 'img', 'publish', 'authors')
# extra_kwargs用来完成反序列化字段的系统校验规则
extra_kwargs = {
'img': {
'required': True,
'error_messages': {
'required': '必填项',
}
}
}

写数据库,无需重写create,ModelSerializer已经实现,所以我们直接写局部钩子和全局钩子即可。
代码语言:javascript复制from rest_framework.serializers import ModelSerializer, SerializerMethodField
from rest_framework.exceptions import ValidationError
from . import models
class PublishModelSerializer(ModelSerializer):
class Meta:
model = models.Publish
fields = ('name', 'address')
class BookModelSerializer(ModelSerializer):
# 了解: 该方式设置的序列化字段,必须在fields中声明
# publish_address = SerializerMethodField()
# def get_publish_address(self, obj):
# return obj.publish.address
# 自定义连表深度 - 子序列化方式
publish = PublishModelSerializer()
class Meta:
# 序列化类关联的model类
model = models.Book
# 参与序列化的字段
fields = ('name', 'price', 'img', 'author_list', 'publish')
# 了解知识点
# 所有字段
# fields = '__all__'
# 与fields不共存,exclude排除哪些字段
# exclude = ('id', 'is_delete', 'create_time')
# 自动连表深度
# depth = 1
class BookModelDeserializer(ModelSerializer):
class Meta:
model = models.Book
fields = ('name', 'price', 'publish', 'authors')
# extra_kwargs 用来完成反序列化字段的 系统校验规则
extra_kwargs = {
'name': {
'required': True,
'min_length': 1,
'error_messages': {
'required': '必填项',
'min_length': '太短',
}
}
}
def validate_name(self, value):
# 书名不能包含 g 字符
if 'g' in value.lower():
raise ValidationError('该g书不能出版')
return value
def validate(self, attrs):
publish = attrs.get('publish')
name = attrs.get('name')
if models.Book.objects.filter(name=name, publish=publish):
raise ValidationError({'book': '该书已存在'})
return attrs
# ModelSerializer类已经帮我们实现了 create 与 update 方法
代码语言:javascript复制from django.db import models
# 图书管理系统:Book、Author、AuthorDetail、Publish
"""
Book表: name、price、img、authors、publish、is_delete、create_time
Publish表: name、address、is_delete、create_time
Author表: name、age、is_delete、create_time
AuthorDetail表: mobile, author、is_delete、create_time
"""
# 1) 基表
class BaseModel(models.Model):
is_delete = models.BooleanField(default=False)
create_time = models.DateTimeField(auto_now_add=True)
# 作为基表的Model不能在数据库中形成对应的表,设置 abstract = True
class Meta:
abstract = True
class Book(BaseModel):
"""name、price、img、authors、publish、is_delete、create_time"""
name = models.CharField(max_length=64)
price = models.DecimalField(max_digits=5, decimal_places=2)
img = models.ImageField(upload_to='img', default='img/default.jpg')
publish = models.ForeignKey(
to='Publish',
db_constraint=False,
related_name='books',
on_delete=models.DO_NOTHING,
)
authors = models.ManyToManyField(
to='Author',
db_constraint=False,
related_name='books'
)
@property
def publish_name(self):
return self.publish.name
@property
def author_list(self):
return self.authors.values('name', 'age', 'detail__mobile').all()
class Meta:
db_table = 'book'
verbose_name = '书籍'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class Publish(BaseModel):
"""name、address、is_delete、create_time"""
name = models.CharField(max_length=64)
address = models.CharField(max_length=64)
class Meta:
db_table = 'publish'
verbose_name = '出版社'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class Author(BaseModel):
"""name、age、is_delete、create_time"""
name = models.CharField(max_length=64)
age = models.IntegerField()
class Meta:
db_table = 'author'
verbose_name = '作者'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class AuthorDetail(BaseModel):
"""mobile, author、is_delete、create_time"""
mobile = models.CharField(max_length=11)
author = models.OneToOneField(
to='Author',
db_constraint=False,
related_name='detail',
on_delete=models.CASCADE,
)
class Meta:
db_table = 'author_detail'
verbose_name = '作者详情'
verbose_name_plural = verbose_name
def __str__(self):
return '%s的详情' % self.author.name
代码语言:javascript复制from rest_framework.views import APIView
from rest_framework.response import Response
from . import models, serializers
class Publish(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
try:
publish_obj = models.Publish.objects.get(pk=pk, is_delete=False)
publish_data = serializers.PublishModelSerializer(publish_obj).data
except:
return Response({
'status': 1,
'msg': '出版社不存在'
})
else:
publish_query = models.Publish.objects.filter(is_delete=False).all()
publish_data = serializers.PublishModelSerializer(publish_query, many=True).data
return Response({
'status': 0,
'msg': 'ok',
'results': publish_data
})
class Book(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
try:
book_obj = models.Book.objects.get(pk=pk, is_delete=False)
book_data = serializers.BookModelSerializer(book_obj).data
except:
return Response({
'status': 1,
'msg': '书籍不存在'
})
else:
book_query = models.Book.objects.filter(is_delete=False).all()
book_data = serializers.BookModelSerializer(book_query, many=True).data
return Response({
'status': 0,
'msg': 'ok',
'results': book_data
})
def post(self, request, *args, **kwargs):
request_data = request.data
book_ser = serializers.BookModelDeserializer(data=request_data)
# 当校验失败,马上终止当前视图方法,抛异常返回给前台
book_ser.is_valid(raise_exception=True)
book_obj = book_ser.save()
return Response({
'status': 0,
'msg': 'ok',
'results': serializers.BookModelSerializer(book_obj).data
})
序列化与反序列化整合 |
---|
路由
代码语言:javascript复制from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^books/$',views.Book.as_view()),
url(r'^books/(?P<pk>.*)/$',views.Book.as_view()),
url(r'^v2/books/$', views.V2Book.as_view()),
url(r'^v2/books/(?P<pk>.*)/$', views.V2Book.as_view()),
]
视图
代码语言:javascript复制from rest_framework.views import APIView
from rest_framework.response import Response
from . import models, serializers
class V2Book(APIView):
# 单查:有pk
# 群查:无pk
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
try:
book_obj = models.Book.objects.get(pk=pk, is_delete=False)
book_data = serializers.V2BookModelSerializer(book_obj).data
except:
return Response({
'status': 1,
'msg': '书籍不存在'
})
else:
book_query = models.Book.objects.filter(is_delete=False).all()
book_data = serializers.V2BookModelSerializer(book_query, many=True).data
return Response({
'status': 0,
'msg': 'ok',
'results': book_data
})
# 单增:传的数据是与model对应的字典
# 群增:传的数据是 装多个 model对应字典 的列表
def post(self, request, *args, **kwargs):
request_data = request.data
if isinstance(request_data, dict):
many = False
elif isinstance(request_data, list):
many = True
else:
return Response({
'status': 1,
'msg': '数据有误',
})
book_ser = serializers.V2BookModelSerializer(data=request_data, many=many)
# 当校验失败,马上终止当前视图方法,抛异常返回给前台
book_ser.is_valid(raise_exception=True)
book_result = book_ser.save()
return Response({
'status': 0,
'msg': 'ok',
'results': serializers.V2BookModelSerializer(book_result, many=many).data
})
# 单删:有pk
# 群删:有pks | {"pks": [1, 2, 3]}
def delete(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
pks = [pk]
else:
pks = request.data.get('pks')
if models.Book.objects.filter(pk__in=pks, is_delete=False).update(is_delete=True):
return Response({
'status': 0,
'msg': '删除成功',
})
return Response({
'status': 1,
'msg': '删除失败',
})
序列化文件
代码语言:javascript复制from rest_framework.serializers import ModelSerializer, SerializerMethodField
from rest_framework.exceptions import ValidationError
from . import models
"""
1) fields中设置所有序列化与反序列化字段
2) extra_kwargs划分只序列化或只反序列化字段
write_only:只反序列化
read_only:只序列化
自定义字段默认只序列化(read_only)
3) 设置反序列化所需的 系统、局部钩子、全局钩子 等校验规则
"""
class V2BookModelSerializer(ModelSerializer):
class Meta:
model = models.Book
fields = ('name', 'price', 'img', 'author_list', 'publish_name', 'publish', 'authors')
extra_kwargs = {
'name': {
'required': True,
'min_length': 1,
'error_messages': {
'required': '必填项',
'min_length': '太短',
}
},
'publish': {
'write_only': True
},
'authors': {
'write_only': True
},
'img': {
'read_only': True,
},
'author_list': {
'read_only': True,
},
'publish_name': {
'read_only': True,
}
}
def validate_name(self, value):
# 书名不能包含 g 字符
if 'g' in value.lower():
raise ValidationError('该g书不能出版')
return value
def validate(self, attrs):
publish = attrs.get('publish')
name = attrs.get('name')
if models.Book.objects.filter(name=name, publish=publish):
raise ValidationError({'book': '该书已存在'})
return attrs
模型
代码语言:javascript复制from django.db import models
# 图书管理系统:Book、Author、AuthorDetail、Publish
"""
Book表: name、price、img、authors、publish、is_delete、create_time
Publish表: name、address、is_delete、create_time
Author表: name、age、is_delete、create_time
AuthorDetail表: mobile, author、is_delete、create_time
"""
# 1) 基表
class BaseModel(models.Model):
is_delete = models.BooleanField(default=False)
create_time = models.DateTimeField(auto_now_add=True)
# 作为基表的Model不能在数据库中形成对应的表,设置 abstract = True
class Meta:
abstract = True
class Book(BaseModel):
"""name、price、img、authors、publish、is_delete、create_time"""
name = models.CharField(max_length=64)
price = models.DecimalField(max_digits=5, decimal_places=2)
img = models.ImageField(upload_to='img', default='img/default.jpg')
publish = models.ForeignKey(
to='Publish',
db_constraint=False,
related_name='books',
on_delete=models.DO_NOTHING,
)
authors = models.ManyToManyField(
to='Author',
db_constraint=False,
related_name='books'
)
@property
def publish_name(self):
return self.publish.name
@property
def author_list(self):
return self.authors.values('name', 'age', 'detail__mobile').all()
class Meta:
db_table = 'book'
verbose_name = '书籍'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class Publish(BaseModel):
"""name、address、is_delete、create_time"""
name = models.CharField(max_length=64)
address = models.CharField(max_length=64)
class Meta:
db_table = 'publish'
verbose_name = '出版社'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class Author(BaseModel):
"""name、age、is_delete、create_time"""
name = models.CharField(max_length=64)
age = models.IntegerField()
class Meta:
db_table = 'author'
verbose_name = '作者'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class AuthorDetail(BaseModel):
"""mobile, author、is_delete、create_time"""
mobile = models.CharField(max_length=11)
author = models.OneToOneField(
to='Author',
db_constraint=False,
related_name='detail',
on_delete=models.CASCADE,
)
class Meta:
db_table = 'author_detail'
verbose_name = '作者详情'
verbose_name_plural = verbose_name
def __str__(self):
return '%s的详情' % self.author.name
单增,群增,单删,群删接口 |
---|
视图
代码语言:javascript复制from rest_framework.views import APIView
from rest_framework.response import Response
from . import models, serializers
class V2Book(APIView):
# 单查:有pk
# 群查:无pk
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
try:
book_obj = models.Book.objects.get(pk=pk, is_delete=False)
book_data = serializers.V2BookModelSerializer(book_obj).data
except:
return Response({
'status': 1,
'msg': '书籍不存在'
})
else:
book_query = models.Book.objects.filter(is_delete=False).all()
book_data = serializers.V2BookModelSerializer(book_query, many=True).data
return Response({
'status': 0,
'msg': 'ok',
'results': book_data
})
# 单增:传的数据是与model对应的字典
# 群增:传的数据是 装多个 model对应字典 的列表
def post(self, request, *args, **kwargs):
request_data = request.data
if isinstance(request_data, dict):
many = False
elif isinstance(request_data, list):
many = True
else:
return Response({
'status': 1,
'msg': '数据有误',
})
book_ser = serializers.V2BookModelSerializer(data=request_data, many=many)
# 当校验失败,马上终止当前视图方法,抛异常返回给前台
book_ser.is_valid(raise_exception=True)
book_result = book_ser.save()
return Response({
'status': 0,
'msg': 'ok',
'results': serializers.V2BookModelSerializer(book_result, many=many).data
})
# 单删:有pk
# 群删:有pks | {"pks": [1, 2, 3]}
def delete(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
pks = [pk]
else:
pks = request.data.get('pks')
if models.Book.objects.filter(pk__in=pks, is_delete=False).update(is_delete=True):
return Response({
'status': 0,
'msg': '删除成功',
})
return Response({
'status': 1,
'msg': '删除失败',
})
class Publish(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
try:
publish_obj = models.Publish.objects.get(pk=pk, is_delete=False)
publish_data = serializers.PublishModelSerializer(publish_obj).data
except:
return Response({
'status': 1,
'msg': '出版社不存在'
})
else:
publish_query = models.Publish.objects.filter(is_delete=False).all()
publish_data = serializers.PublishModelSerializer(publish_query, many=True).data
return Response({
'status': 0,
'msg': 'ok',
'results': publish_data
})
class Book(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
try:
book_obj = models.Book.objects.get(pk=pk, is_delete=False)
book_data = serializers.BookModelSerializer(book_obj).data
except:
return Response({
'status': 1,
'msg': '书籍不存在'
})
else:
book_query = models.Book.objects.filter(is_delete=False).all()
book_data = serializers.BookModelSerializer(book_query, many=True).data
return Response({
'status': 0,
'msg': 'ok',
'results': book_data
})
def post(self, request, *args, **kwargs):
request_data = request.data
book_ser = serializers.BookModelDeserializer(data=request_data)
# 当校验失败,马上终止当前视图方法,抛异常返回给前台
book_ser.is_valid(raise_exception=True)
book_obj = book_ser.save()
return Response({
'status': 0,
'msg': 'ok',
'results': serializers.BookModelSerializer(book_obj).data
})
模型
代码语言:javascript复制from django.db import models
# 图书管理系统:Book、Author、AuthorDetail、Publish
"""
Book表: name、price、img、authors、publish、is_delete、create_time
Publish表: name、address、is_delete、create_time
Author表: name、age、is_delete、create_time
AuthorDetail表: mobile, author、is_delete、create_time
"""
# 1) 基表
class BaseModel(models.Model):
is_delete = models.BooleanField(default=False)
create_time = models.DateTimeField(auto_now_add=True)
# 作为基表的Model不能在数据库中形成对应的表,设置 abstract = True
class Meta:
abstract = True
class Book(BaseModel):
"""name、price、img、authors、publish、is_delete、create_time"""
name = models.CharField(max_length=64)
price = models.DecimalField(max_digits=5, decimal_places=2)
img = models.ImageField(upload_to='img', default='img/default.jpg')
publish = models.ForeignKey(
to='Publish',
db_constraint=False,
related_name='books',
on_delete=models.DO_NOTHING,
)
authors = models.ManyToManyField(
to='Author',
db_constraint=False,
related_name='books'
)
@property
def publish_name(self):
return self.publish.name
@property
def author_list(self):
return self.authors.values('name', 'age', 'detail__mobile').all()
class Meta:
db_table = 'book'
verbose_name = '书籍'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class Publish(BaseModel):
"""name、address、is_delete、create_time"""
name = models.CharField(max_length=64)
address = models.CharField(max_length=64)
class Meta:
db_table = 'publish'
verbose_name = '出版社'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class Author(BaseModel):
"""name、age、is_delete、create_time"""
name = models.CharField(max_length=64)
age = models.IntegerField()
class Meta:
db_table = 'author'
verbose_name = '作者'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class AuthorDetail(BaseModel):
"""mobile, author、is_delete、create_time"""
mobile = models.CharField(max_length=11)
author = models.OneToOneField(
to='Author',
db_constraint=False,
related_name='detail',
on_delete=models.CASCADE,
)
class Meta:
db_table = 'author_detail'
verbose_name = '作者详情'
verbose_name_plural = verbose_name
def __str__(self):
return '%s的详情' % self.author.name
序列化
代码语言:javascript复制from rest_framework.serializers import ModelSerializer, SerializerMethodField
from rest_framework.exceptions import ValidationError
from . import models
class PublishModelSerializer(ModelSerializer):
class Meta:
model = models.Publish
fields = ('name', 'address')
class BookModelSerializer(ModelSerializer):
# 了解: 该方式设置的序列化字段,必须在fields中声明
# publish_address = SerializerMethodField()
# def get_publish_address(self, obj):
# return obj.publish.address
# 自定义连表深度 - 子序列化方式
publish = PublishModelSerializer()
class Meta:
# 序列化类关联的model类
model = models.Book
# 参与序列化的字段
fields = ('name', 'price', 'img', 'author_list', 'publish')
# 了解知识点
# 所有字段
# fields = '__all__'
# 与fields不共存,exclude排除哪些字段
# exclude = ('id', 'is_delete', 'create_time')
# 自动连表深度
# depth = 1
class BookModelDeserializer(ModelSerializer):
class Meta:
model = models.Book
fields = ('name', 'price', 'publish', 'authors')
# extra_kwargs 用来完成反序列化字段的 系统校验规则
extra_kwargs = {
'name': {
'required': True,
'min_length': 1,
'error_messages': {
'required': '必填项',
'min_length': '太短',
}
}
}
def validate_name(self, value):
# 书名不能包含 g 字符
if 'g' in value.lower():
raise ValidationError('该g书不能出版')
return value
def validate(self, attrs):
publish = attrs.get('publish')
name = attrs.get('name')
if models.Book.objects.filter(name=name, publish=publish):
raise ValidationError({'book': '该书已存在'})
return attrs
# ModelSerializer类已经帮我们实现了 create 与 update 方法
"""
1) fields中设置所有序列化与反序列化字段
2) extra_kwargs划分只序列化或只反序列化字段
write_only:只反序列化
read_only:只序列化
自定义字段默认只序列化(read_only)
3) 设置反序列化所需的 系统、局部钩子、全局钩子 等校验规则
"""
class V2BookModelSerializer(ModelSerializer):
class Meta:
model = models.Book
fields = ('name', 'price', 'img', 'author_list', 'publish_name', 'publish', 'authors')
extra_kwargs = {
'name': {
'required': True,
'min_length': 1,
'error_messages': {
'required': '必填项',
'min_length': '太短',
}
},
'publish': {
'write_only': True
},
'authors': {
'write_only': True
},
'img': {
'read_only': True,
},
'author_list': {
'read_only': True,
},
'publish_name': {
'read_only': True,
}
}
def validate_name(self, value):
# 书名不能包含 g 字符
if 'g' in value.lower():
raise ValidationError('该g书不能出版')
return value
def validate(self, attrs):
publish = attrs.get('publish')
name = attrs.get('name')
if models.Book.objects.filter(name=name, publish=publish):
raise ValidationError({'book': '该书已存在'})
return attrs
单整体改 |
---|
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models, serializers
class V2Book(APIView):
# 单查:有pk
# 群查:无pk
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
try:
book_obj = models.Book.objects.get(pk=pk, is_delete=False)
book_data = serializers.V2BookModelSerializer(book_obj).data
except:
return Response({
'status': 1,
'msg': '书籍不存在'
})
else:
book_query = models.Book.objects.filter(is_delete=False).all()
book_data = serializers.V2BookModelSerializer(book_query, many=True).data
return Response({
'status': 0,
'msg': 'ok',
'results': book_data
})
# 单增:传的数据是与model对应的字典
# 群增:传的数据是 装多个 model对应字典 的列表
def post(self, request, *args, **kwargs):
request_data = request.data
if isinstance(request_data, dict):
many = False
elif isinstance(request_data, list):
many = True
else:
return Response({
'status': 1,
'msg': '数据有误',
})
book_ser = serializers.V2BookModelSerializer(data=request_data, many=many)
# 当校验失败,马上终止当前视图方法,抛异常返回给前台
book_ser.is_valid(raise_exception=True)
book_result = book_ser.save()
return Response({
'status': 0,
'msg': 'ok',
'results': serializers.V2BookModelSerializer(book_result, many=many).data
})
# 单删:有pk
# 群删:有pks | {"pks": [1, 2, 3]}
def delete(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
pks = [pk]
else:
pks = request.data.get('pks')
if models.Book.objects.filter(pk__in=pks, is_delete=False).update(is_delete=True):
return Response({
'status': 0,
'msg': '删除成功',
})
return Response({
'status': 1,
'msg': '删除失败',
})
# 单整体改,传的数据是与model对应的字典{name|price|publish|authors}
def put(self, request, *args, **kwargs):
request_data = request.data
pk = kwargs.get('pk')
old_book_obj = models.Book.objects.filter(pk=pk).first()
## 将众多 数据的校验交给序列化类来 处理,让序列化累扮演反序列化的角色,校验成功后,序列化帮你入库
book_ser = serializers.V2BookModelSerializer(instance=old_book_obj, data=request_data)
book_ser.is_valid(raise_exception=True)
# 校验通过,完成数据的更新:要知道更新的目标,用来更新的新数据
book_obj = book_ser.save()
return Response({
'status': 0,
'msg': 'put OK',
'results': serializers.V2BookModelSerializer(book_obj).data
})


单局部改 |
---|
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models, serializers
class V2Book(APIView):
# 单查:有pk
# 群查:无pk
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
try:
book_obj = models.Book.objects.get(pk=pk, is_delete=False)
book_data = serializers.V2BookModelSerializer(book_obj).data
except:
return Response({
'status': 1,
'msg': '书籍不存在'
})
else:
book_query = models.Book.objects.filter(is_delete=False).all()
book_data = serializers.V2BookModelSerializer(book_query, many=True).data
return Response({
'status': 0,
'msg': 'ok',
'results': book_data
})
# 单增:传的数据是与model对应的字典
# 群增:传的数据是 装多个 model对应字典 的列表
def post(self, request, *args, **kwargs):
request_data = request.data
if isinstance(request_data, dict):
many = False
elif isinstance(request_data, list):
many = True
else:
return Response({
'status': 1,
'msg': '数据有误',
})
book_ser = serializers.V2BookModelSerializer(data=request_data, many=many)
# 当校验失败,马上终止当前视图方法,抛异常返回给前台
book_ser.is_valid(raise_exception=True)
book_result = book_ser.save()
return Response({
'status': 0,
'msg': 'ok',
'results': serializers.V2BookModelSerializer(book_result, many=many).data
})
# 单删:有pk
# 群删:有pks | {"pks": [1, 2, 3]}
def delete(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
pks = [pk]
else:
pks = request.data.get('pks')
if models.Book.objects.filter(pk__in=pks, is_delete=False).update(is_delete=True):
return Response({
'status': 0,
'msg': '删除成功',
})
return Response({
'status': 1,
'msg': '删除失败',
})
# 单整体改,传的数据是与model对应的字典{name|price|publish|authors}
def put(self, request, *args, **kwargs):
request_data = request.data
pk = kwargs.get('pk')
old_book_obj = models.Book.objects.filter(pk=pk).first()
## 将众多 数据的校验交给序列化类来 处理,让序列化累扮演反序列化的角色,校验成功后,序列化帮你入库
book_ser = serializers.V2BookModelSerializer(instance=old_book_obj, data=request_data)
book_ser.is_valid(raise_exception=True)
# 校验通过,完成数据的更新:要知道更新的目标,用来更新的新数据
book_obj = book_ser.save()
return Response({
'status': 0,
'msg': 'put OK',
'results': serializers.V2BookModelSerializer(book_obj).data
})
# 单局部改
def patch(self,request,*args,**kwargs):
request_data = request.data
pk = kwargs.get('pk')
old_book_obj = models.Book.objects.filter(pk=pk).first()
## 将众多 数据的校验交给序列化类来 处理,让序列化累扮演反序列化的角色,校验成功后,序列化帮你入库
book_ser = serializers.V2BookModelSerializer(instance=old_book_obj, data=request_data,partial=True)
book_ser.is_valid(raise_exception=True)
# 校验通过,完成数据的更新:要知道更新的目标,用来更新的新数据
book_obj = book_ser.save()
return Response({
'status': 0,
'msg': 'put OK',
'results': serializers.V2BookModelSerializer(book_obj).data
})

群改接口 |
---|
请求数据应该是列表套字典:[{},{},{}] 或者字典套字典: {"1":{},"2":{},"3":{}}
群改需要使用ListSerializer,并且要重写update方法
代码语言:javascript复制from rest_framework.serializers import ModelSerializer, SerializerMethodField
from rest_framework.exceptions import ValidationError
from . import models
class PublishModelSerializer(ModelSerializer):
class Meta:
model = models.Publish
fields = ('name', 'address')
class BookModelSerializer(ModelSerializer):
# 了解: 该方式设置的序列化字段,必须在fields中声明
# publish_address = SerializerMethodField()
# def get_publish_address(self, obj):
# return obj.publish.address
# 自定义连表深度 - 子序列化方式
publish = PublishModelSerializer()
class Meta:
# 序列化类关联的model类
model = models.Book
# 参与序列化的字段
fields = ('name', 'price', 'img', 'author_list', 'publish')
# 了解知识点
# 所有字段
# fields = '__all__'
# 与fields不共存,exclude排除哪些字段
# exclude = ('id', 'is_delete', 'create_time')
# 自动连表深度
# depth = 1
class BookModelDeserializer(ModelSerializer):
class Meta:
model = models.Book
fields = ('name', 'price', 'publish', 'authors')
# extra_kwargs 用来完成反序列化字段的 系统校验规则
extra_kwargs = {
'name': {
'required': True,
'min_length': 1,
'error_messages': {
'required': '必填项',
'min_length': '太短',
}
}
}
def validate_name(self, value):
# 书名不能包含 g 字符
if 'g' in value.lower():
raise ValidationError('该g书不能出版')
return value
def validate(self, attrs):
publish = attrs.get('publish')
name = attrs.get('name')
if models.Book.objects.filter(name=name, publish=publish):
raise ValidationError({'book': '该书已存在'})
return attrs
# ModelSerializer类已经帮我们实现了 create 与 update 方法
"""
1) fields中设置所有序列化与反序列化字段
2) extra_kwargs划分只序列化或只反序列化字段
write_only:只反序列化
read_only:只序列化
自定义字段默认只序列化(read_only)
3) 设置反序列化所需的 系统、局部钩子、全局钩子 等校验规则
"""
from rest_framework.serializers import ListSerializer
# 重点:ListSerializer与ModelSerializer建立关联的是:
# ModelSerializer的Meta类的 - list_serializer_class
class V2BookListSerializer(ListSerializer):
def update(self, instance, validated_data):
# print(instance) # 要更新的对象们
# print(validated_data) # 更新的对象对应的数据们
# print(self.child) # 服务的模型序列化类 - V2BookModelSerializer
for index, obj in enumerate(instance):
self.child.update(obj, validated_data[index])
return instance
class V2BookModelSerializer(ModelSerializer):
class Meta:
model = models.Book
fields = ('name', 'price', 'img', 'author_list', 'publish_name', 'publish', 'authors')
extra_kwargs = {
'name': {
'required': True,
'min_length': 1,
'error_messages': {
'required': '必填项',
'min_length': '太短',
}
},
'publish': {
'write_only': True
},
'authors': {
'write_only': True
},
'img': {
'read_only': True,
},
'author_list': {
'read_only': True,
},
'publish_name': {
'read_only': True,
}
}
# 群改,需要设置 自定义ListSerializer,重写群改的 update 方法
list_serializer_class = V2BookListSerializer
def validate_name(self, value):
# 书名不能包含 g 字符
if 'g' in value.lower():
raise ValidationError('该g书不能出版')
return value
def validate(self, attrs):
publish = attrs.get('publish')
name = attrs.get('name')
if models.Book.objects.filter(name=name, publish=publish):
raise ValidationError({'book': '该书已存在'})
return attrs
代码语言:javascript复制from rest_framework.views import APIView
from rest_framework.response import Response
from . import models, serializers
class Publish(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
try:
publish_obj = models.Publish.objects.get(pk=pk, is_delete=False)
publish_data = serializers.PublishModelSerializer(publish_obj).data
except:
return Response({
'status': 1,
'msg': '出版社不存在'
})
else:
publish_query = models.Publish.objects.filter(is_delete=False).all()
publish_data = serializers.PublishModelSerializer(publish_query, many=True).data
return Response({
'status': 0,
'msg': 'ok',
'results': publish_data
})
class Book(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
try:
book_obj = models.Book.objects.get(pk=pk, is_delete=False)
book_data = serializers.BookModelSerializer(book_obj).data
except:
return Response({
'status': 1,
'msg': '书籍不存在'
})
else:
book_query = models.Book.objects.filter(is_delete=False).all()
book_data = serializers.BookModelSerializer(book_query, many=True).data
return Response({
'status': 0,
'msg': 'ok',
'results': book_data
})
def post(self, request, *args, **kwargs):
request_data = request.data
book_ser = serializers.BookModelDeserializer(data=request_data)
# 当校验失败,马上终止当前视图方法,抛异常返回给前台
book_ser.is_valid(raise_exception=True)
book_obj = book_ser.save()
return Response({
'status': 0,
'msg': 'ok',
'results': serializers.BookModelSerializer(book_obj).data
})
class V2Book(APIView):
# 单查:有pk
# 群查:无pk
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
try:
book_obj = models.Book.objects.get(pk=pk, is_delete=False)
book_data = serializers.V2BookModelSerializer(book_obj).data
except:
return Response({
'status': 1,
'msg': '书籍不存在'
})
else:
book_query = models.Book.objects.filter(is_delete=False).all()
book_data = serializers.V2BookModelSerializer(book_query, many=True).data
return Response({
'status': 0,
'msg': 'ok',
'results': book_data
})
# 单增:传的数据是与model对应的字典
# 群增:传的数据是 装多个 model对应字典 的列表
def post(self, request, *args, **kwargs):
request_data = request.data
if isinstance(request_data, dict):
many = False
elif isinstance(request_data, list):
many = True
else:
return Response({
'status': 1,
'msg': '数据有误',
})
book_ser = serializers.V2BookModelSerializer(data=request_data, many=many)
# 当校验失败,马上终止当前视图方法,抛异常返回给前台
book_ser.is_valid(raise_exception=True)
book_result = book_ser.save()
return Response({
'status': 0,
'msg': 'ok',
'results': serializers.V2BookModelSerializer(book_result, many=many).data
})
# 单删:有pk
# 群删:有pks | {"pks": [1, 2, 3]}
def delete(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
pks = [pk]
else:
pks = request.data.get('pks')
if models.Book.objects.filter(pk__in=pks, is_delete=False).update(is_delete=True):
return Response({
'status': 0,
'msg': '删除成功',
})
return Response({
'status': 1,
'msg': '删除失败',
})
# 单整体改: 对 v2/books/(pk)/ 传的数据是与model对应的字典{name|price|publish|authors}
def put(self, request, *args, **kwargs):
request_data = request.data
pk = kwargs.get('pk')
old_book_obj = models.Book.objects.filter(pk=pk).first()
# 目的:将众多数据的校验交给序列化类来处理 - 让序列化类扮演反序列化角色,校验成功后,序列化类来帮你入库
book_ser = serializers.V2BookModelSerializer(instance=old_book_obj, data=request_data, partial=False)
book_ser.is_valid(raise_exception=True)
# 校验通过,完成数据的更新:要更新的目标,用来更新的新数据
book_obj = book_ser.save()
return Response({
'status': 0,
'msg': 'ok',
'results': serializers.V2BookModelSerializer(book_obj).data
})
# 单局部改:对 v2/books/(pk)/ 传的数据,数据字段key都是选填
# 群局部改:
# 请求数据 - [{pk:1, name:123}, {pk:3, price:7}, {pk:7, publish:2}]
def patch(self, request, *args, **kwargs):
request_data = request.data
pk = kwargs.get('pk')
# 将单改,群改的数据都格式化成 pks=[要需要的对象主键标识] | request_data=[每个要修改的对象对应的修改数据]
if pk and isinstance(request_data, dict): # 单改
pks = [pk, ]
request_data = [request_data, ]
elif not pk and isinstance(request_data, list): # 群改
pks = []
for dic in request_data: # 遍历前台数据[{pk:1, name:123}, {pk:3, price:7}, {pk:7, publish:2}],拿一个个字典
pk = dic.pop('pk', None)
if pk:
pks.append(pk)
else:
return Response({
'status': 1,
'msg': '数据有误',
})
else:
return Response({
'status': 1,
'msg': '数据有误',
})
# pks与request_data数据筛选,
# 1)将pks中的没有对应数据的pk与数据已删除的pk移除,request_data对应索引位上的数据也移除
# 2)将合理的pks转换为 objs
objs = []
new_request_data = []
for index, pk in enumerate(pks):
try:
# pk对应的数据合理,将合理的对象存储
obj = models.Book.objects.get(pk=pk,is_delete=False)
objs.append(obj)
# 对应索引的数据就需要保存下来
new_request_data.append(request_data[index])
except:
# 重点:反面教程 - pk对应的数据有误,将对应索引的data中request_data中移除
# index = pks.index(pk)
# request_data.pop(index)
continue
book_ser = serializers.V2BookModelSerializer(instance=objs, data=new_request_data, partial=True, many=True)
book_ser.is_valid(raise_exception=True)
book_objs = book_ser.save()
return Response({
'status': 0,
'msg': 'ok',
'results': serializers.V2BookModelSerializer(book_objs, many=True).data
})
# 总结:
"""
1)单整体修改:
V2BookModelSerializer(
instance=要被更新的对象,
data=用来更新的数据,
partial=默认False,必须的字段全部参与校验
)
2)单局部修改:
V2BookModelSerializer(
instance=要被更新的对象,
data=用来更新的数据,
partial=设置True,必须的字段都变为选填字段
)
注:partial设置True的本质就是使字段 required=True 校验规则失效
"""