一:多表设计
(1)模型表字段
""" 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 BaseModel基表 is_delete、create_time 上面四表继承基表,可以继承两个字段 """
PS:
(1)表格都有是否删除字段 创建时间字段
(2)抽象继承一个模型表(基表)
(2)基表的创建
class BaseModel(models.Model): is_delete = models.BooleanField(default=False) create_time = models.DateTimeField(auto_now_add=True) # 设置 abstract = True 来声明基表,作为基表的Model不能在数据库中形成对应的表 重点 class Meta: abstract = True
(3)断关联多表关系
(1)作用:
(1)物理上断开关系提升查找效率
(2)防止环装表关系 导致表关系成为死表(即不能再操作表 如果想要在重新操作表格 需要删库跑路)
(2)字段设计
1:外键字段 (1)一对多:外键存放在多的一方 (2)一对一:从逻辑正反向考虑 如作者与作者详情 作者删除 作者详情级联更新 作者详情删除 作者还在 因此将外键存放在详情表中 (3)多对多:在关系表中 2:ORM查询 (1)正向查询:通过外键字段 (2)反向查询:听过ralated_name (3)连表操作关系 (1)作者删除--->作者详情删除---->cascade (2)作者删除--->作者详情为空---->set_null (3)作者删除--->作者详情默认---->set-defalut (4)作者删除--->作者详情无损---->do_nothing
# 作者详情表中的 author = models.OneToOneField( to='Author', related_name='detail', db_constraint=False, on_delete=models.CASCADE ) # 图书表中的 publish = models.ForeignKey( to='Publish', related_name='books', db_constraint=False, on_delete=models.DO_NOTHING, ) authors = models.ManyToManyField( to='Author' related_name='books', db_constraint=False, )
PS:
(1)多对多表关系不能设置on_delete
(2)一对一,一对多必须设置on_delete
(3)1.X的Django默认设置on_delete 2.X需要手工设置
(4)模型表创建
# 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', # 反向查询字段:publish_obj.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
二:ModelSerializer
(1)settings文件配置
INSTALLED_APPS = [ # 注册rest_framework 'rest_framework', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database', 'USER': 'root', 'PASSWORD': '123', } } """ 任何__init__文件 import pymysql pymysql.install_as_MySQLdb() """ LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = False MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
(2)主路由层配置
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}), ]
(3)子路由层
from django.conf.urls import url from . import views urlpatterns = [ url('^books/$', views.Book.as_view()), url('^books/(?P<primary_key>.*)/$', views.Book.as_view()), url(r'^v2/books/$', views.V2Book.as_view()), url(r'^v2/books/(?P<pk>.*)/$', views.V2Book.as_view()), ]
(3)序列化层:
(1)项目下创建一下py文件
serializers.py
(2)导入相应的模块
from rest_framework.serializers import ModelSerializer, SerializerMethodField from rest_framework.exceptions import ValidationError # 导入报错信息 from . import models # 导入模型表
(3)基础使用方式
class BookModelSerializer(ModelSerializer): # 创建序列化类class Meta: model = models.Book # 序列化类关联的model类 后面根据类目相当于拿到类的名称空间 fields = ('name', 'price', 'img', 'author_info', ) # 参与序列化的字段
(4)自定义连表深度
# 可以单独作为Publish接口的序列化类,也可以作为Book序列化外键publish辅助的序列化组件 class PublishModelSerializer(ModelSerializer): class Meta: model = models.Publish fields = ('name', 'address') class BookModelSerializer(ModelSerializer): # 自定义连表深度 - 子序列化方式 - 该方式不能参与反序列化,使用在序列化反序列化共存时,不能书写 publish = PublishModelSerializer() class Meta: # 序列化类关联的model类 model = models.Book # 参与序列化的字段 fields = ('name', 'price', 'img', 'author_info','publish' )
(5)小特性了解知识点
class BookModelSerializer(ModelSerializer): # 了解: 该方式设置的序列化字段,必须在fields中声明 publish_address = SerializerMethodField() def get_publish_address(self, obj): return obj.publish.address fields = '__all__' # 所有字段 exclude = ('id', 'is_delete', 'create_time') # 与fields不共存,exclude排除哪些字段 depth = 1 # 自动连表深度
(6)视图层查询数据
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 })
(7)序列化层
class PublishModelSerializer(ModelSerializer): class Meta: model = models.Publish fields = ('name', 'address') class BookModelSerializer(ModelSerializer): # 自定义连表深度 - 子序列化方式 - 该方式不能参与反序列化,使用在序列化反序列化共存时,不能书写 publish = PublishModelSerializer() class Meta: # 序列化类关联的model类 model = models.Book # 参与序列化的字段 fields = ('name', 'price', 'img', 'author_info', 'publish')
(8)视图层数据提交
class Book(APIView): def post(self, request, *args, **kwargs): request_data = request.data book_ser = serializers.BookModelDeserializer(data=request_data) # raise_exception=True:当校验失败,马上终止当前视图方法,抛异常返回给前台 book_ser.is_valid(raise_exception=True) book_obj = book_ser.save() return Response({ 'status': 0, 'msg': 'ok', 'results': serializers.BookModelSerializer(book_obj).data })
(9)反序列化层
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 设置哪些字段是只参与序列化与参与反序列化
(1)read_only ---> 只参与序列化
(2)write_only ---> 只参与反序列化
(3)设置全局钩子 局部钩子 以及需要校验的字段
(4)代码展示
class V2BookModelDeSerializer(ModelSerializer): class Meta: model = models.Book # 参与序列化的模型表 fields = ('name', 'price', 'img', 'authors_info', '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
(5)视图层代码变动
class V2Book(APIView): # 查询 def get(self, request, *args, **kwargs): primary_key = kwargs.get('primary_key') if not primary_key: book_obj_list = models.Book.objects.filter(is_delete=False).all() # 查询所有没被删除的对象 book_data = serializers.V2BookModelDeSerializer(book_obj_list, many=True).data return Response({ 'status': 0, 'msg': 'ok', 'results': book_data }) try: book_obj = models.Book.objects.get(pk=primary_key, is_delete=False) book_data = serializers.V2BookModelDeSerializer(book_obj).data except: return Response({ 'msg': '查询错误 该书籍不存在', 'status': 1 }) return Response({ 'status': 0, 'msg': 'ok', 'results': book_data }) # 添加 def post(self, request, *args, **kwargs): request_data = request.data if isinstance(request_data, dict) and request_data is not None: many = False # 添加单条数据 elif isinstance(request_data, list) and request_data is not None: many = True # 添加多条数据 else: return Response({ 'status': 1, 'msg': '数据错误' }) book_ser = serializers.V2BookModelDeSerializer(data=request_data, many=many) if book_ser.is_valid(raise_exception=True): # 当前校验设备 立马终止程序运行 抛出异常 book_results = book_ser.save() book_data = serializers.V2BookModelDeSerializer(book_results, many=many).data # many = many一定加上 因为序列化的假设多个数据 还需要将参与序列化的数据给返回出去 return Response({ 'status': 0, 'msg': 'ok', 'results': book_data }) def delete(self, request, *args, **kwargs): primary_key = kwargs.get('primary_key') data = request.data if primary_key: pks = [primary_key] # 删除多条数据 else: pks = data.get('pks') # 获取前台传入的多个数据 print(pks) book_obj = models.Book.objects.filter(pk__in=pks, is_delete=False) # 判断后端的pk在不在上述列表中 且筛选没有被删除的字段 if book_obj: book_obj.update(is_delete=True) return Response({ 'status': 1, 'msg': '删除失败' }) return Response({ 'status': 0, 'msg': '删除成功', })
(6)单条数据整体更改
def put(self, request, *args, **kwargs): pk = kwargs.get('primary_key') # 获取更改的对象的主键 通过主键进行筛选 request_data = request.data # 获取更改数据的值 try: book_obj = models.Book.objects.filter(pk=pk).first() # 进行异常捕获 防止前端输入的pk不是整形 except: return Response( { 'status': 1, 'msg': '数据不存在', }) ''' instance:要更改的模型表实例化产生的对象 data:要更改的数据 ''' book_ser = serializers.BookModelSerializer(instance=book_obj, data=request_data) book_ser.is_valid(raise_exception=True) book_ser_obj = book_ser.save() data = serializers.BookModelSerializer(book_ser_obj).data return Response( { 'status': 0, 'msg': 'ok', 'results': data } )
(7)单条局部修改
def patch(self, request, *args, **kwargs): pk = kwargs.get('primary_key') request_data = request.data # 要更改的数据 try: book_obj = models.Book.objects.filter(pk=pk).first() # 要更改模型表实例化的对象 except: return Response( { 'status': 1, 'msg': '数据不存在', }) ''' instance:要更改模型表实例化的对象 data:要更改的数据 partial:设置部分字段可以选填 ''' book_ser = serializers.BookModelSerializer(instance=book_obj,data=request_data,partial=True) book_ser.is_valid(raise_exception=True) book_ser_obj = book_ser.save() data = serializers.BookModelSerializer(book_ser_obj).data return Response( { 'status': 0, 'msg': 'ok', 'results': data } )
(8)单改与局部整体修改
# 序列化层 class BookListSerializer(ListSerializer): def update(self, instance, validated_data): print(instance) # 要更新的对象们 print(validated_data) # 更新的对象对应的数据们 print(self.child) # 服务的模型序列化类 - BookModelSerializer for index, obj in enumerate(instance): self.child.update(obj, validated_data[index]) # 获取需要更新的对象 以及更新的数据 return instance class BookModelSerializer(ModelSerializer): class Meta: # 群改,需要设置 自定义ListSerializer,重写群改的 update 方法 list_serializer_class = BookListSerializer
PS:
(1)由于源码问题 我们需要自己定义ListSerializer的update方法
(9)视图层
def patch(self, request, *args, **kwargs): pk = kwargs.get('primary_key') request_data = request.data # [{'pk': 1, 'name': 123}, {'pk': 3, 'price': 7}, {'pk': 7, 'publish': 2}] 前台传入的数据 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 = dic.pop('pk', None) # for循环上述数据 将主键传入上述列表 如果设置none防止主键不存在 if not pk: return Response( { 'status': 2, 'msg': '数据错误' } ) pks.append(pk) # 将主键加入上述列表 else: return Response( { 'status': 1, 'msg': "数据查询错误" } ) objs = [] # 存放序列化的对象 new_request_data = [] # 存放需要反序列化的数据 for index, pk in enumerate(pks): try: # 防止主键不存在 obj = models.Book.objects.get(pk=pk,is_delete=False) objs.append(obj) new_request_data.append(request_data[index]) # 上述pks都是合法的主键 通过获取主键的索引 然后去原数据取值 except: # 主键不存在 直接跳出本次循环 进入下一次循环 # 重点:反面教程 - pk对应的数据有误,将对应索引的data中request_data中移除 # index = pks.index(pk) # request_data.pop(index) continue book_ser = serializers.BookModelSerializer(instance=objs, data=new_request_data, many=True, partial=True) book_ser.is_valid(raise_exception=True) book_obj = book_ser.save() data = serializers.BookModelSerializer(book_obj, many=True).data return Response({ 'status': 0, 'msg': "ok", "results": data })
四:视图类与序列化类传参
(1)作用:
(1)某些序列化类可能会需要视图层的数据
(2)context可以让序列化类获取视图类内部的参数
(2)使用方式
(1)视图类在序列化的时候传入context的方法
(2)序列化类通过self.context拿到传入的数据
(3)视图类
class Book(APIView): def post(self, request, *args, **kwargs): book_ser = serializers.BookModelSerializer(data=request_data,context={'request':request}) book_ser.is_valid(raise_exception=True) book_result = book_ser.save() return Response({ 'status': 0, 'msg': 'ok', 'results': serializers.BookModelSerializer(book_result).data })
(4)序列化类
class BookModelSerializer(ModelSerializer): class Meta: model = models.Book fields = ('name', 'price') def validate_name(self, value): print(self.context.get('request').method) # 拿到后端使用的方法 return value
五:Reponse封装
from rest_framework.response import Response class APIResponse(Response): ''' data_status:数据状态码 data_msg:数据返回消息 headers:请求头 results:响应结果 exception:报错信息 http_status:http状态码 kwargs:后端是否传入额外数据 例如token等 ''' def __init__(self, data_status=0, data_msg='ok', headers=None, results=None, exception=False, http_status=None, **kwargs): data = { 'status': data_status, 'msg': data_msg } ''' Response({ 'status': 0, 'msg': 'ok', 'results': [], 'token': '' # 有这样的额外的key-value数据结果 },status=http_status,headers=headers,exception=True|False) APIResponse() => Response({'status': 0,'msg': 'ok'}) # # ''' # 判断是否有返回结果 如果有则返回 if results is not None: data['results'] = results # 判断后端时候给序列化传额外数据 if kwargs is not None: data.update(kwargs) super().__init__(data=data, status=http_status, exception=exception, headers=headers) """ Response({ 'status': 0, 'msg': 'ok', 'results': [], 'token': '' # 有这样的额外的key-value数据结果 },status=http_status,headers=headers,exception=True|False) APIResponse() => Response({'status': 0,'msg': 'ok'}) """