增删改查

对应的Serializer序列化器
针对于Serializer创建与更新方法需要重写,删除、查询、查询单个需要在视图类中完成

  1. class BookSerializer(serializers.Serializer):
  2. bname = serializers.CharField(max_length=20)
  3. price = serializers.DecimalField(max_digits=5, decimal_places=2)
  4. def update(self, instance, validated_data):
  5. instance.bname = validated_data.get('bname')
  6. instance.price = validated_data.get('price')
  7. instance.save()
  8. return instance
  9. def create(self, validated_data):
  10. book_obj = Book.objects.create(**validated_data)
  11. return book_obj

对应视图类

  1. class BookApiView(views.APIView):
  2. def get(self,request):
  3. dict = {{'code':200, 'msg':'查询成功成功'}}
  4. if not request.query_params:
  5. books = Book.objects.all()
  6. dict['msg'] = '查询全部书籍成功'
  7. else :
  8. books = Book.objects.filter(pk=request.query_params.get('id'))
  9. dict['msg'] = '查询一本书籍成功'
  10. bookSerializer = BookSerializer(instance=books, many=True)
  11. dict['data'] = bookSerializer.data
  12. return Response(dict)
  13. def delete(self,request):
  14. dict = {'code':200}
  15. pk = request.data.get('id')
  16. if pk:
  17. book_obj = Book.objects.filter(pk=pk)
  18. if book_obj:
  19. book_obj.delete()
  20. dict['msg'] = '删除成功'
  21. dict['data'] = ''
  22. else :
  23. dict['code'] = 10003
  24. dict['msg'] = '该书不存在,无法删除'
  25. else:
  26. dict['code'] = 10004
  27. dict['msg'] = '请指定书籍id'
  28. return Response(dict)
  29. def put(self,request):
  30. dict = {'code': 200}
  31. book_obj = Book.objects.filter(pk=request.data.get('id')).first()
  32. if book_obj:
  33. bookSerializer = BookSerializer(instance=book_obj, data=request.data)
  34. if bookSerializer.is_valid():
  35. bookSerializer.save()
  36. dict['msg'] = '修改成功'
  37. dict['data'] = bookSerializer.data
  38. else:
  39. dict['code'] = 10001
  40. dict['msg'] = '修改失败,数据未通过验证'
  41. dict['errors'] = bookSerializer.errors
  42. else:
  43. dict['code'] = 10002
  44. dict['msg'] = '不存在该书籍'
  45. dict['errors'] = '找不到对应的书籍id'
  46. return Response(dict)
  47. def post(self,request):
  48. print(request.FILES)
  49. dict = {'code': 200}
  50. bookSerializer = BookSerializer(data=request.data)
  51. if bookSerializer.is_valid():
  52. bookSerializer.save()
  53. dict['msg'] = '创建成功'
  54. dict['data'] = bookSerializer.data
  55. else:
  56. dict['code'] = 10005
  57. dict['msg'] = '数据验证未通过'
  58. dict['errors'] = bookSerializer.errors
  59. return Response(dict)

Serializer字段与参数

常见字段与models基本一致
常用参数:
read_only:True 不设置时默认为False 作用是只在序列化时产生该字段数据
write_only:True 不设置时默认为False 作用是只在反序列化时需要该字段数据
error_messages 设置该字段检验不通过的错误信息
depth 连表查询深度

Serializer局部和全局钩子

局部钩子是重写validate_字段名 函数
需要抛出错误时使用ValidationError
通过验证时返回对应的字段

  1. def validate_pname(self, pname):
  2. if re.findall('京东', pname):
  3. raise ValidationError('出版社名字不能包含京东')
  4. else:
  5. return pname

全局钩子是重写validate函数 在全局钩子中attrs是对应序列化器中的所有字段
需要抛出错误时使用ValidationError
通过验证时返回对应的attrs

  1. def validate(self, attrs):
  2. if re.findall('日本', attrs.get('address')):
  3. raise ValidationError('出版社地址不能在日本')
  4. return attrs