settings.py
INSTALLED_APPS = [
# ...
'rest_framework',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dg_proj',
'USER': 'root',
'PASSWORD': '123',
}
}
# 连接mysql数据库
"""
任何__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')
models.py
"""
Book表:name、price、img、authors、publish、is_delete、create_time
Pbulish表:name、address、is_delete、create_time
Author表:name、age、is_delete、create_time
AutherDetail表:mobile、author、is_delete、create_time
BaseModel基表
is_delete、create_tiime
上面四个表的创建继承基表。可以继承两个字段
"""
"""
外键处理:
反向查询名字:related_name
表关系:db_constraint + on_delete
db_constraint=False => 断开表关系
on_delete=models.CASCADE 级联
on_delete=models.SET_NULL, null=True 设置为空
on_delete=models.SET_DEFAULT, default=0 设置成默认值0
on_delete=models.DO_NOTHING 不处理
注:多对多关系不需要明确on_delete
"""
"""
1、外键位置:
一对多 - 外键放多的一方
一对一 - 从逻辑正反向考虑,如作者表与作者详情表,作者删除级联删除详情,
详情删除作者依旧存在,所以建议外键在详情表中
多对多 - 外键在关系表中
2、ORM正向方向连表查找:
正向:通过外键字段 eg: author_detial_obj.author
反向:通过related_name的值 eg:author_obj.detail
注:依赖代码见下方
3、连表操作关系:
1)作者删除,详情级联 - on_delete=models.CASCADE
2)作者删除,详情置空 - null=True, on_delete=models.SET_NULL
3)作者删除,详情重置 - default=0, on_delete=models.SET_DEFAULT
4)作者删除,详情不动 - on_delete=models.DO_NOTHING
注:拿作者与作者详情表举例
4、外键关联字段的参数 - 如何实现 断关联、目前表间操作关系、方向查询字段
i)作者详情表中的
author = models.OneToOneField(
to='Author',
related_name='detail',
db_constraint=False,
on_delete=models.CASCADE
)
ii)图书表中的
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,
)
注:ManyToManyField不能设置on_delete,OneToOneField、
ForeignKey必须设置on_delete(django1.x系统默认级联,
但是django2.x必须手动明确)
"""
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)
# 设置 abstract =True 来声明基表,作为基表的Model不能在数据库中形成对应的表
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
serialiaers.py
from rest_framework.serializers import ModelSerializer, SerializerMethodField
from rest_framework.exceptions import ValidationError
from . import models
# 可以单独作为Publish接口的序列化类,也可以作为Book序列化外键publish辅助的序列化组件
class PublishModelSerializer(ModelSerializer):
class Meta:
model = models.Publish
fields = ('name', 'address')
class BookModelSerializer1(ModelSerializer):
# 了解: 该方式设置的序列化字段,必须在fields中声明
# publish_address = SerializerMethodField()
# def get_publish_address(self, obj):
# return obj.publish.address
# 自定义连表深度 - 子序列化方式 - 该方式不能参与反序列化,使用在序列化反序列化共存时,不能书写
publish = PublishModelSerializer() ## 获取关于publish所有属性
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 BookModelDeserializer2(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划分只序列化字段
wirte_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
views.py
from rest_framework.response import Response
from rest_framework.views import APIView
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, is_delete=False)
book_data = serializers.BookModelSerializer1(book_obj).data
except:
return Response({
'status': 1,
'msg': '书籍不存在'
})
else:
book_query = models.Book.objects.filter(is_delete=False).all()
book_data = serializers.BookModelSerializer1(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.BookModelDeserializer2(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.BookModelSerializer1(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': '删除失败',
})
urls.py
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()),
]
案例
"""
models.py
"""
from django.db import models
class BaseModel(models.Model):
is_delete=models.BooleanField(default=False)
# auto_now_add=True 只要记录创建,不需要手动插入时间,自动把当前时间插入
create_time=models.DateTimeField(auto_now_add=True)
# auto_now=True,只要更新,就会把当前时间插入
last_update_time=models.DateTimeField(auto_now=True)
# import datetime
# create_time=models.DateTimeField(default=datetime.datetime.now)
class Meta:
# 单个字段,有索引,有唯一
# 多个字段,有联合索引,联合唯一
abstract=True # 抽象表,不再数据库建立出表
class Book(BaseModel):
id=models.AutoField(primary_key=True)
# verbose_name admin中显示中文
name=models.CharField(max_length=32,verbose_name='书名',help_text='这里填书名')
price=models.DecimalField(max_digits=5,decimal_places=2)
# 一对多的关系一旦确立,关联字段写在多的一方
#to_field 默认不写,关联到Publish主键
#db_constraint=False 逻辑上的关联,实质上没有外键练习,增删不会受外键影响,但是orm查询不影响
publish=models.ForeignKey(to='Publish',on_delete=models.DO_NOTHING,db_constraint=False)
# 多对多,跟作者,关联字段写在 查询次数多的一方
# 什么时候用自动,什么时候用手动?第三张表只有关联字段,用自动 第三张表有扩展字段,需要手动写
# 不能写on_delete
authors=models.ManyToManyField(to='Author',db_constraint=False)
class Meta:
verbose_name_plural='图书' # admin中表名的显示
ordering = ['id'] # 按id排序
def __str__(self):
return self.name
@property
def publish_name(self):
return self.publish.name
# def author_list(self):
def author_list(self):
# return self.authors.all().values()
author_list=self.authors.all()
# ll=[]
# for author in author_list:
# ll.append({'name':author.name,'sex':author.get_sex_display()})
# return ll
return [ {'name':author.name,'sex':author.get_sex_display()} for author in author_list]
class Publish(BaseModel):
name = models.CharField(max_length=32)
addr=models.CharField(max_length=32)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = '出版社'
class Author(BaseModel):
name=models.CharField(max_length=32)
sex=models.IntegerField(choices=((1,'男'),(2,'女')))
# 一对一关系,写在查询频率高的一方
#OneToOneField本质就是ForeignKey+unique,自己手写也可以
authordetail=models.OneToOneField(to='AuthorDetail',db_constraint=False,on_delete=models.CASCADE)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = '作者'
class AuthorDetail(BaseModel):
mobile=models.CharField(max_length=11)
class Meta:
verbose_name_plural = '作者详情'
def __str__(self):
return self.mobile
# 二、表断关联
# 1、表之间没有外键关联,但是有外键逻辑关联(有充当外键的字段)
# 2、断关联后不会影响数据库查询效率,但是会极大提高数据库增删改效率(不影响增删改查操作)
# 3、断关联一定要通过逻辑保证表之间数据的安全,不要出现脏数据,代码控制
# 4、断关联
# 5、级联关系
# 作者没了,详情也没:on_delete=models.CASCADE
# 出版社没了,书还是那个出版社出版:on_delete=models.DO_NOTHING
# 部门没了,员工没有部门(空不能):null=True, on_delete=models.SET_NULL
# 部门没了,员工进入默认部门(默认值):default=0, on_delete=models.SET_DEFAULT
"""
admin.py
"""
from django.contrib import admin
# Register your models here.
from app02 import models
admin.site.register(models.Book)
admin.site.register(models.Publish)
admin.site.register(models.Author)
admin.site.register(models.AuthorDetail)
"""
serializers.py
"""
from rest_framework import serializers
from app02 import models
## 重写ListSerializer中的update方法(源码中群更新update方法没写)
class BookListSerializer(serializers.ListSerializer):
def update(self, instance, validated_data):
return [
self.child.update(instance[i], attr) for i,attr in enumerate(validated_data)
]
class BookModelSerializer(serializers.ModelSerializer):
class Meta:
## 关联群跟新update方法
list_serializer_class = BookListSerializer
model = models.Book
fields = ['name', 'price', 'authors', 'publish', 'author_list', 'publish_name',]
extra_kwargs = {
'authors': {'write_only':True,},
'publish': {'write_only':True,},
'author_list': {'read_only':True,},
'publish_name': {'read_only':True,},
}
"""
views.py
"""
from django.shortcuts import render
from rest_framework.generics import GenericAPIView
from app02.serializers import BookModelSerializer
from app02 import models
from utils.response import RespUtil
from rest_framework.pagination import PageNumberPagination
# Create your views here.
from rest_framework.serializers import ListSerializer
class SelfPagination(PageNumberPagination):
page_size = 3
page_size_query_param = "size"
max_page_size = 5
class BookGenericAPIView(GenericAPIView):
queryset = models.Book.objects.all().filter(is_delete=False)
serializer_class = BookModelSerializer
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
ser = self.serializer_class(self.get_object())
else:
# 若分页报警告(UnorderedObjectListWarning)在需要进行查询的模型类中增加ordering参数(在class Meta中加)或在需要进行查询的语句中增加order_by排序
page_obj = SelfPagination()
book_list = page_obj.paginate_queryset(self.get_queryset(), request, self)
# next_url = page_obj.get_next_link()
# pr_url = page_obj.get_previous_link()
ser = self.serializer_class(book_list, many=True)
return RespUtil(data=ser.data)
def post(self, request, *args, **kwargs):
if isinstance(request.data, dict):
ser = self.serializer_class(data=request.data)
else:
ser = self.serializer_class(data=request.data, many=True)
ser.is_valid(raise_exception=True)
ser.save()
return RespUtil(data=ser.data)
def put(self, request, *args, **kwargs):
if kwargs.get('pk'):
book = models.Book.objects.filter(pk=kwargs.get('pk')).first()
ser = self.serializer_class(instance=book, data=request.data, partial=True)
else:
obj = []
data = []
for item in request.data:
pk = item.pop('id')
book = models.Book.objects.filter(pk=pk).first()
obj.append(book)
data.append(item)
## 不重写update方法循环调用update方法一个个跟新也行
# for i, v in enumerate(data):
# ser = self.serializer_class(instance=obj[i], data=v)
# ser.is_valid(raise_exception=True)
# ser.save()
ser = self.serializer_class(instance=obj, data=data, many=True)
ser.is_valid(raise_exception=True)
ser.save()
return RespUtil(data=ser.data)
def delete(self, request, *args, **kwargs):
pk = kwargs.get('pk')
pks = []
if pk:
pks.append(pk)
else:
pks = request.data.get('pks')
res = models.Book.objects.filter(id__in=pks, is_delete=False).update(is_delete=True)
if res:
return RespUtil(msg='OK')
return RespUtil(msg='无要删除的数据')
"""
urls.py
"""
from django.conf.urls import url
from app02 import views
urlpatterns = [
url(r'^v2/books/$', views.BookGenericAPIView.as_view()),
url(r'^v2/books/(?P<pk>d+)/', views.BookGenericAPIView.as_view()),
]
老师版
# views.py
from django.shortcuts import render
# Create your views here.
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from app01.models import Book
# from app01.ser import BookSerializers
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
# class TestView(APIView):
# def get(self,request):
# 1/0
# return Response({'msg':'个人中心'})
#
# class BookViewSet(ModelViewSet):
# authentication_classes = [BasicAuthentication,]
# queryset = Book.objects.all()
# serializer_class = BookSerializers
# @action(methods=['get'], detail=False)
# def login(self, request):
# Book.objects.update_or_create()
# return Response({'msg':'登陆成功'})
# @action(methods=['put'], detail=True)
# def get_new_5(self, request,pk):
# return Response({'msg':'获取5条数据成功'})
from rest_framework.permissions import AllowAny,IsAuthenticated,IsAdminUser,IsAuthenticatedOrReadOnly
from app01.response import APIResponse
from app01 import models
from app01 import ser as serializers
class PublishAPIView(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
publish_obj = models.Publish.objects.filter(pk=pk).first()
if not publish_obj:
return APIResponse(1, 'pk error', http_status=400)
publish_data = serializers.PublishModelSerializer(publish_obj).data
return APIResponse(results=publish_data)
publish_query = models.Publish.objects.all()
return APIResponse(0, 'ok', data=serializers.PublishModelSerializer(publish_query, many=True).data)
class BookAPIView(APIView):
# 单查、群查
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
book_obj = models.Book.objects.filter(pk=pk, is_delete=False).first()
if not book_obj:
return APIResponse(1, 'pk error', http_status=400)
book_data = serializers.BookModelSerializer(book_obj).data
print(book_data)
return APIResponse(data=book_data)
book_query = models.Book.objects.filter(is_delete=False).all()
return APIResponse(0, 'ok', data=serializers.BookModelSerializer(book_query, many=True).data)
# 单删、群删
def delete(self, request, *args, **kwargs):
"""
单删:前台数据为pk,接口为 /books/(pk)/
群删:前台数据为pks,接口为 /books/
"""
pk = kwargs.get('pk')
# 将单删群删逻辑整合
if pk: # /books/(pk)/的接口就不考虑群删,就固定为单删
pks = [pk]
else:
pks = request.data.get('pks')
# 前台数据有误(主要是群删没有提供pks)
if not pks:
return APIResponse(1, 'delete error', http_status=400)
# 只要有操作受影响行,就是删除成功,反之失败
rows = models.Book.objects.filter(is_delete=False, pk__in=pks).update(is_delete=True)
if rows:
return APIResponse(0, 'delete ok')
return APIResponse(1, 'delete failed')
# 单增、群增
def post(self, request, *args, **kwargs):
"""
单增:前台提交字典,接口 /books/
群增:前台提交列表套字典,接口 /books/
"""
request_data = request.data
if isinstance(request_data, dict): # 单增
book_ser = serializers.BookModelSerializer(data=request_data)
if book_ser.is_valid():
book_obj = book_ser.save()
return APIResponse(data=serializers.BookModelSerializer(book_obj).data)
return APIResponse(1, msg=book_ser.errors)
elif isinstance(request_data, list) and len(request_data) != 0 : # 群增
book_ser = serializers.BookModelSerializer(data=request_data, many=True)
book_ser.is_valid(raise_exception=True)
book_obj_list = book_ser.save()
return APIResponse(data=serializers.BookModelSerializer(book_obj_list, many=True).data)
else:
return APIResponse(1, 'data error', http_status=400)
# 单整体改、群整体改
def put(self, request, *args, **kwargs):
"""
单整体改:前台提交字典,接口 /books/(pk)/
群整体改:前台提交列表套字典,接口 /books/,注每一个字典都可以通过pk
"""
pk = kwargs.get('pk')
request_data = request.data
if pk: # 单改
try:
book_obj = models.Book.objects.get(pk=pk)
except:
return APIResponse(1, 'pk error')
# 修改和新增,都需要通过数据,数据依旧给data,修改与新增不同点,instance要被赋值为被修改对象
book_ser = serializers.BookModelSerializer(instance=book_obj, data=request_data)
book_ser.is_valid(raise_exception=True)
book_obj = book_ser.save()
return APIResponse(data=serializers.BookModelSerializer(book_obj).data)
else: # 群改
if not isinstance(request_data, list) or len(request_data) == 0:
return APIResponse(1, 'data error', http_status=400)
# [{pk:1,...}, {pk:3,...}, {pk:100,...}] => [obj1, obj3, obj100] + [{...}, {...}, {...}]
# 要考虑pk对应的对象是否被删,以及pk没有对应的对象
# 假设pk3被删,pk100没有 => [obj1] + [{...}]
# 注:一定不要在循环体中对循环对象进行增删(影响对象长度)的操作
obj_list = []
data_list = []
for dic in request_data:
# request_data可能是list,单内部不一定是dict
try:
pk = dic.pop('pk')
try:
obj = models.Book.objects.get(pk=pk, is_delete=False)
obj_list.append(obj)
data_list.append(dic)
except:
pass
except:
return APIResponse(1, 'data error', http_status=400)
book_ser = serializers.BookModelSerializer(instance=obj_list, data=data_list, many=True)
book_ser.is_valid(raise_exception=True)
book_obj_list = book_ser.save()
return APIResponse(data=serializers.BookModelSerializer(book_obj_list, many=True).data)
# 单局部改、群局部改
def patch(self, request, *args, **kwargs):
"""
单整体改:前台提交字典,接口 /books/(pk)/
群整体改:前台提交列表套字典,接口 /books/,注每一个字典都可以通过pk
"""
pk = kwargs.get('pk')
request_data = request.data
if pk:
try:
book_obj = models.Book.objects.get(pk=pk)
except:
return APIResponse(1, 'pk error')
# 局部修改就是在整体修改基础上设置partial=True,将所有参与反序列化字段设置为required=False
book_ser = serializers.BookModelSerializer(instance=book_obj, data=request_data, partial=True)
book_ser.is_valid(raise_exception=True)
book_obj = book_ser.save()
return APIResponse(data=serializers.BookModelSerializer(book_obj).data)
else: # 群改
if not isinstance(request_data, list) or len(request_data) == 0:
return APIResponse(1, 'data error', http_status=400)
# [{pk:1,...}, {pk:3,...}, {pk:100,...}] => [obj1, obj3, obj100] + [{...}, {...}, {...}]
# 要考虑pk对应的对象是否被删,以及pk没有对应的对象
# 假设pk3被删,pk100没有 => [obj1] + [{...}]
# 注:一定不要在循环体中对循环对象进行增删(影响对象长度)的操作
obj_list = []
data_list = []
for dic in request_data:
# request_data可能是list,单内部不一定是dict
try:
pk = dic.pop('pk')
try:
obj = models.Book.objects.get(pk=pk, is_delete=False)
obj_list.append(obj)
data_list.append(dic)
except:
pass
except:
return APIResponse(1, 'data error', http_status=400)
book_ser = serializers.BookModelSerializer(instance=obj_list, data=data_list, many=True, partial=True)
book_ser.is_valid(raise_exception=True)
book_obj_list = book_ser.save()
return APIResponse(data=serializers.BookModelSerializer(book_obj_list, many=True).data)
class AuthorAPIView(APIView):
def get(self,request,*args,**kwargs):
authors=models.Author.objects.all()
author_ser=serializers.AuthorModelSerializer(authors,many=True)
return APIResponse(data=author_ser.data)
def put(self,reuqest,*args,**kwargs):
pass
def post(self,request,*args,**kwargs):
author_ser=serializers.AuthorModelSerializer(data=request.data)
author_ser.is_valid(raise_exception=True)
author_ser.save()
return APIResponse()
def delete(self,request,*args,**kwargs):
pass
# ser.py
from rest_framework import serializers
from app01 import models
class BookListSerializer(serializers.ListSerializer):
# 1、create方法父级ListSerializer已经提供了
# def create(self, validated_data):
# # 通过self.child来访问绑定的ModelSerializer
# print(self.child)
# raise Exception('我不提供')
# 2、父级ListSerializer没有通过update方法的实现体,需要自己重写
def update(self, instance, validated_data):
# print(instance)
# print(validated_data)
return [
self.child.update(instance[i], attrs) for i, attrs in enumerate(validated_data)
]
class BookModelSerializer(serializers.ModelSerializer):
# 通过BookModelSerializer.Meta.list_serializer_class来访问绑定的ListSerializer
class Meta:
# 关联ListSerializer完成群增群改
list_serializer_class = BookListSerializer
model = models.Book
# fields = ('name', 'price', 'publish', 'authors')
# fields = ('name', 'price', 'publish_name', 'author_list')
# 了解
# fields = '__all__'
# exclude = ('id', )
# depth = 1
# 序列化与反序列化整合
fields = ('name', 'price', 'publish_name', 'author_list', 'publish', 'authors')
extra_kwargs = {
'publish': {
'write_only': True
},
'authors': {
'write_only': True
}
}
# 前提:如果只有查需求的接口,自定义深度还可以用子序列化方式完成
class PublishModelSerializer(serializers.ModelSerializer):
# 子序列化都是提供给外键(正向方向)完成深度查询的,外键数据是唯一:many=False;不唯一:many=True
# 注:只能参与序列化,且反序列化不能写(反序列化外键字段会抛异常)
books = BookModelSerializer(many=True)
class Meta:
model = models.Publish
fields = ('name', 'address', 'books')
class AuthorModelSerializer(serializers.ModelSerializer):
class Meta:
model=models.Author
fields=('name','sex','mobile','mobile_in')
extra_kwargs={
'mobile':{
'read_only': True
},
}
mobile_in=serializers.CharField(write_only=True)
# def validate_mobile_in(self, data):
# print(data)
# return data
def create(self, validated_data):
print(validated_data)
mobile=validated_data.pop('mobile_in')
author=models.Author.objects.create(**validated_data)
authordetail=models.AuthorDetail.objects.create(mobile=mobile,author=author)
return author
# models.py
from django.db import models
# 一、基表
# Model类的内部配置Meta类要设置abstract=True,这样的Model类就是用来作为基表
# 多表:Book,Publish,Author,AuthorDetail
class BaseModel(models.Model):
is_delete = models.BooleanField(default=False)
create_time = models.DateTimeField(auto_now_add=True)
class Meta:
# 基表必须设置abstract,基表就是给普通Model类继承使用的,设置了abstract就不会完成数据库迁移完成建表
abstract = True
class Book(BaseModel):
name = models.CharField(max_length=16)
price = models.DecimalField(max_digits=5, decimal_places=2)
publish = models.ForeignKey(to='Publish', related_name='books', db_constraint=False, on_delete=models.DO_NOTHING)
# 重点:多对多外键实际在关系表中,ORM默认关系表中两个外键都是级联
# ManyToManyField字段不提供设置on_delete,如果想设置关系表级联,只能手动定义关系表
authors = models.ManyToManyField(to='Author', related_name='books', db_constraint=False)
# 自定义连表深度,不需要反序列化,因为自定义插拔属性不参与反序列化
@property
def publish_name(self):
return self.publish.name
@property
def author_list(self):
temp_author_list = []
for author in self.authors.all():
temp_author_list.append({
'name': author.name,
'sex': author.get_sex_display(),
'mobile': author.detail.mobile
})
return temp_author_list
class Publish(BaseModel):
name = models.CharField(max_length=16)
address = models.CharField(max_length=64)
class Author(BaseModel):
name = models.CharField(max_length=16)
sex = models.IntegerField(choices=[(0, '男'),(1, '女')], default=0)
class AuthorDetail(BaseModel):
mobile = models.CharField(max_length=11)
# 有作者可以没有详情,删除作者,详情一定会被级联删除
# 外键字段为正向查询字段,related_name是反向查询字段
author = models.OneToOneField(to='Author', related_name='detail', db_constraint=False, on_delete=models.CASCADE)
# 二、表断关联
# 1、表之间没有外键关联,但是有外键逻辑关联(有充当外键的字段)
# 2、断关联后不会影响数据库查询效率,但是会极大提高数据库增删改效率(不影响增删改查操作)
# 3、断关联一定要通过逻辑保证表之间数据的安全
# 4、断关联
# 5、级联关系
# 作者没了,详情也没:on_delete=models.CASCADE
# 出版社没了,书还是那个出版社出版:on_delete=models.DO_NOTHING
# 部门没了,员工没有部门(空不能):null=True, on_delete=models.SET_NULL
# 部门没了,员工进入默认部门(默认值):default=0, on_delete=models.SET_DEFAULT
# 三、ORM外键设计
# 1、一对多:外键放在多的一方
# 2、多对多:外键放在常用的一方
# 3、一对一:外键放在不常用的一方
# 4、外键字段为正向查询字段,related_name是反向查询字段
# from django.contrib.auth.models import AbstractUser, User
# class MyUser(AbstractUser):
# pass
# setting.py
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# urls.py
path(r'publishes/', views.PublishAPIView.as_view()),
re_path(r'^publishes/(?P<pk>d+)/$', views.PublishAPIView.as_view()),
path(r'books/', views.BookAPIView.as_view()),
re_path(r'^books/(?P<pk>d+)/$', views.BookAPIView.as_view()),