一。拆分的序列化。
model序列化的基本用法就是使用元类中的fields,其中model绑定的就是model中的表
如果需要多表查询,要在model中定义property:
class BookModelSerializer(ModelSerializer):
publish = PublishModelSerializer() class Meta:
model = models.Book
fields = ('name', 'price', 'img', 'author_list', 'publish')
model该表中的property方法:
@property
def publish_name(self):
return self.publish.name @property
def author_list(self):
return self.authors.values('name', 'age','detail__mobile').all()
这些都是model中的字段。
第二种就是使用外接的序列化类生成序列化对象,然后作为字段添加到field中。这种设定不是可插拔式的。
class PublishModelSerializer(ModelSerializer):
class Meta:
model = models.Publish
fields = ('name', 'address') class BookModelSerializer(ModelSerializer): publish = PublishModelSerializer() class Meta:
model = models.Book
fields = ('name', 'price', 'img', 'author_list', 'publish')
第三种不常用,就是使用field。exclude除了这立马的字段之外其他都显示,另加depth作为深度。
class BookModelSerializer(ModelSerializer):
publish = PublishModelSerializer()
class Meta:
model = models.Book
fields = ('name', 'price', 'img', 'author_list', 'publish')
# 了解知识点
# 所有字段
# fields = '__all__'
# 与fields不共存,exclude排除哪些字段
# exclude = ('id', 'is_delete', 'create_time')
# 自动连表深度
# depth = 1
这些序列化类在被定义之后,在view视图层种调用,调用的参数有instance,date和many
instance是需要序列化的对象,date是从前端接受的数据,many就是是否为多单位。
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
})
view
反序列化使用:
重新继承一个modelserializer类,反序列化需要使用元类字段extra_kwargs。
这个是其他关键字段,其中的元素就是fields种的字段,字段种使用字段进行判断:
required:是否必填。
min_length等长度提示,
error_messages则是以上限时生效的时候返回给前端的错误信息。
进行反序列化后可以通过钩子函数(局部和全局)进判断。
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 方法
serializers
这个模块已经帮我们实现了create和update,只需要在前端调用save方法即可。
二。整合的序列化。
在序列化类中,有以下信息:
model = models.book 模块的定义
fields = 操作的字段定义。
extra_kwargs 对字段的操作
在对字段的操作中,有三选一的操作:
required:True 是否必填。
read_only 只能序列化。
write_only 只能反序列化。
"""
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
整合的序列化
三。单查询和群查询。
主要通过路由传输参数pk,判断是否有pk如果有pk则为单查,如果没有pk则为群查。
'''
单查路由:http://127.0.0.1:8000/api/v2/books/1/
单查数据返回:{
"status": 0,
"msg": "ok",
"results": {
"name": "南开大学",
"price": "12.00",
"img": "/media/img/default.jpg",
"publish_name": "东京出版社",
}
}
群查路由:http://127.0.0.1:8000/api/v2/books
群查数据返回:{
"status": 0,
"msg": "ok",
"results": [
{
"name": "南开大学",
"price": "12.00",
"img": "/media/img/default.jpg",
"publish_name": "东京出版社",
"author_list": [
{
"id": 1,
"is_delete": false,
"create_time": "2019-10-17T11:09:29.316398",
"name": "zzj",
"age": 12
},
{
"id": 2,
"is_delete": false,
"create_time": "2019-10-17T11:10:21.914888",
"name": "zzp",
"age": 43
}
]
},
{
"name": "南开大学",
"price": "12.00",
"img": "/media/img/default.jpg",
"publish_name": "东京出版社",
"author_list": [
{
"id": 1,
"is_delete": false,
"create_time": "2019-10-17T11:09:29.316398",
"name": "zzj",
"age": 12
},
{
"id": 2,
"is_delete": false,
"create_time": "2019-10-17T11:10:21.914888",
"name": "zzp",
"age": 43
}
]
}
]
}
'''
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
})
四,单增和多增。
增加的逻辑就是判断传入的数据是否是字典或列表,是字典则是单个,列表则是多个
'''
增添路由:http://127.0.0.1:8000/api/v2/books/
单增输入:
{
"name":"南开大学12",
"price":12,
"publish":1,
"authors":[1,2]
}
多增输入:
[
{
"name":"南开大学1",
"price":12,
"publish":1,
"authors":[1,2]
},
{
"name":"南开大学2",
"price":12,
"publish":1,
"authors":[1,2]
}
]
数据返回:
{
"status": 0,
"msg": "ok",
"results": {
"name": "南开大学12",
"price": "12.00",
"img": "/media/img/default.jpg",
"publish_name": "东京出版社",
}
}
''' 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,而如果没有pk,则会获取传入参数 的数据中的pks。
最后都生成列表以并操作。
'''
单删路由:http://127.0.0.1:8000/api/v2/books/7/
多删路由:http://127.0.0.1:8000/api/v2/books/
多删输入:{"pks": [1, 2, 3]}
返回数据{
"status": 0,
"msg": "删除成功"
}
'''
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': '删除失败',
})
六。整体单改
修改主要取决于序列化对象中的参数partial和所有字段中的required对象
"""
1) 单整体改,说明前台要提供修改的数据,那么数据就需要校验,
校验的数据应该在实例化“序列化类对象”时,赋值给data
2)修改,就必须明确被修改的模型类对象,并在实例化“序列化类对象”时,赋值给instance
3)整体修改,所有校验规则有required=True的字段,都必须提供,因为在实例化“序列化类对象”时,
参数partial默认为False
注:如果partial值设置为True,就是可以局部改
1)单整体修改,一般用put请求:
V2BookModelSerializer(
instance=要被更新的对象,
data=用来更新的数据,
partial=默认False,必须的字段全部参与校验
)
2)单局部修改,一般用patch请求:
V2BookModelSerializer(
instance=要被更新的对象,
data=用来更新的数据,
partial=设置True,必须的字段都变为选填字段
)
注:partial设置True的本质就是使字段 required=True 校验规则失效
"""
对于单体全修改,使用put来提交数据。
如果系列化对象中同时存在对象和数据时,就会修改该数据:
'''
修改路由:http://127.0.0.1:8000/api/v2/books/7/
修改输入:
{
"name":"南开大学123",
"price":12,
"publish":1,
"authors":[1,2]
}(所有必填字段都要)
'''
class V2Book(APIView):
# 单整体改: 对 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
})
七。单改和群局部修改。
只需要修改被改的对象。
首先通过是否有pk和传入的修改数据对象类型进行判断,同一替换成列表。
群体修改的数据需要一一对应。然后弹出pk。
其中需要定义listserializer中的update方法,重写,可以调用子的update方法进行重写。
# 重点: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:
# ...
# 群改,需要设置 自定义ListSerializer,重写群改的 update 方法
list_serializer_class = V2BookListSerializer
# ...
视图:
'''
单局部修改路由:http://127.0.0.1:8000/api/v2/books/7/
单局部修改输入:{"name":"南开大学1234"}
群局部修改路由:http://127.0.0.1:8000/api/v2/books/
群局部修改输入:[
{"pk":1, "name":"123"},
{"pk":3, "price":7},
{"pk":7, "publish":2}
] '''
class V2Book(APIView):
# 单局部改:对 v2/books/(pk)/ 传的数据,数据字段key都是选填
# 群局部改:对 v2/books/
# 请求数据 - [{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)
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
})
总结:
model层:
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
model
exception层:
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('%s - %s - %s' % (context['view'], context['request'].method, exc))
return Response({
'detail': '服务器错误'
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True)
return response
exception
serializers层:
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
serializer
url:
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'^publishes/$', views.Publish.as_view()),
url(r'^publishes/(?P<pk>.*)/$', views.Publish.as_view()), url(r'^v2/books/$', views.V2Book.as_view()),
url(r'^v2/books/(?P<pk>.*)/$', views.V2Book.as_view()),
]
urls
view层:
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)
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 校验规则失效
"""
view