增删改查
对应的Serializer序列化器
针对于Serializer创建与更新方法需要重写,删除、查询、查询单个需要在视图类中完成
class BookSerializer(serializers.Serializer):
bname = serializers.CharField(max_length=20)
price = serializers.DecimalField(max_digits=5, decimal_places=2)
def update(self, instance, validated_data):
instance.bname = validated_data.get('bname')
instance.price = validated_data.get('price')
instance.save()
return instance
def create(self, validated_data):
book_obj = Book.objects.create(**validated_data)
return book_obj
对应视图类
class BookApiView(views.APIView):
def get(self,request):
dict = {{'code':200, 'msg':'查询成功成功'}}
if not request.query_params:
books = Book.objects.all()
dict['msg'] = '查询全部书籍成功'
else :
books = Book.objects.filter(pk=request.query_params.get('id'))
dict['msg'] = '查询一本书籍成功'
bookSerializer = BookSerializer(instance=books, many=True)
dict['data'] = bookSerializer.data
return Response(dict)
def delete(self,request):
dict = {'code':200}
pk = request.data.get('id')
if pk:
book_obj = Book.objects.filter(pk=pk)
if book_obj:
book_obj.delete()
dict['msg'] = '删除成功'
dict['data'] = ''
else :
dict['code'] = 10003
dict['msg'] = '该书不存在,无法删除'
else:
dict['code'] = 10004
dict['msg'] = '请指定书籍id'
return Response(dict)
def put(self,request):
dict = {'code': 200}
book_obj = Book.objects.filter(pk=request.data.get('id')).first()
if book_obj:
bookSerializer = BookSerializer(instance=book_obj, data=request.data)
if bookSerializer.is_valid():
bookSerializer.save()
dict['msg'] = '修改成功'
dict['data'] = bookSerializer.data
else:
dict['code'] = 10001
dict['msg'] = '修改失败,数据未通过验证'
dict['errors'] = bookSerializer.errors
else:
dict['code'] = 10002
dict['msg'] = '不存在该书籍'
dict['errors'] = '找不到对应的书籍id'
return Response(dict)
def post(self,request):
print(request.FILES)
dict = {'code': 200}
bookSerializer = BookSerializer(data=request.data)
if bookSerializer.is_valid():
bookSerializer.save()
dict['msg'] = '创建成功'
dict['data'] = bookSerializer.data
else:
dict['code'] = 10005
dict['msg'] = '数据验证未通过'
dict['errors'] = bookSerializer.errors
return Response(dict)
Serializer字段与参数
常见字段与models基本一致
常用参数:
read_only:True 不设置时默认为False 作用是只在序列化时产生该字段数据
write_only:True 不设置时默认为False 作用是只在反序列化时需要该字段数据
error_messages 设置该字段检验不通过的错误信息
depth 连表查询深度
Serializer局部和全局钩子
局部钩子是重写validate_字段名 函数
需要抛出错误时使用ValidationError
通过验证时返回对应的字段
def validate_pname(self, pname):
if re.findall('京东', pname):
raise ValidationError('出版社名字不能包含京东')
else:
return pname
全局钩子是重写validate函数 在全局钩子中attrs是对应序列化器中的所有字段
需要抛出错误时使用ValidationError
通过验证时返回对应的attrs
def validate(self, attrs):
if re.findall('日本', attrs.get('address')):
raise ValidationError('出版社地址不能在日本')
return attrs