1 序列化器-Serializer
1
21. 序列化,序列化器会把模型对象转换成字典,经过response以后变成json字符串
32. 反序列化,把客户端发送过来的数据,经过request以后变成字典,序列化器可以把字典转成模型
43. 反序列化,完成数据校验功能
2 序列化器的序列化
2.1 基本使用
2.1.1 视图层views.py
1from django.shortcuts import render
2
3
4
5
6
7
8
9
10
11from rest_framework.views import APIView
12from app01.models import Book
13
14
15from .serializer import BookSerializer
16from rest_framework.response import Response
17
18
19
20
21
22
23
24
25
26
27class BookView(APIView):
28 def get(self, request, *args, **kwargs):
29
30 books = Book.objects.all()
31
32
33
34 print(books)
35 ser = BookSerializer(instance=books, many=True)
36 print(ser.data)
37
38
39 return Response(data=ser.data)
40
41
42 def post(self, request, *args, **kwargs):
43
44
45
46
47
48
49 ser = BookSerializer(data=request.data)
50
51 if ser.is_valid():
52 ser.save()
53 return Response(ser.data)
54 else:
55 return Response(ser.errors)
56
57
58class BookDetailView(APIView):
59 def get(self, request, pk):
60
61 books = Book.objects.all().filter(pk=pk).first()
62 ser = BookSerializer(instance=books)
63
64 return Response(data=ser.data)
65
66 def delete(self, request, pk):
67
68 Book.objects.all().filter(pk=pk).delete()
69 return Response()
70
71 def put(self, request, pk):
72 book = Book.objects.filter(pk=pk).first()
73
74 ser = BookSerializer(instance=book, data=request.data)
75
76 if ser.is_valid():
77 ser.save()
78 return Response(ser.data)
2.1.2 序列化器serializer.py
1
2from rest_framework import serializers
3from .models import Book
4from rest_framework.exceptions import ValidationError
5
6
7class BookSerializer(serializers.Serializer):
8
9 title = serializers.CharField(max_length=8, min_length=3)
10 price = serializers.IntegerField()
11
12
13 publish = serializers.CharField()
14
15
16 def create(self, validated_data):
17 book = Book.objects.create(**validated_data)
18 return book
19
20
21 def update(self, instance, validated_data):
22 instance.title = validated_data.get('title')
23 instance.price = validated_data.get('price')
24 instance.publish = validated_data.get('publish')
25 instance.save()
26 return instance
27
28
29 def validate_title(self, item):
30 print(item)
31
32 if item.startswith('sb'):
33 raise ValidationError('不能以sb开头')
34
35 return item
36
37
38 def validate(self, attrs):
39
40 if attrs.get('title') == attrs.get('publish'):
41 raise ValidationError('标题和出版社不能一样')
42
43 return attrs
2.1.3 表模型 models.py
1from django.db import models
2
3
4
5
6
7class Book(models.Model):
8 title = models.CharField(max_length=32,default='红')
9 price = models.IntegerField(default='0')
10
11 publish = models.CharField(max_length=32,default='出')
2.1.4 路由urls.py
1from app01 import views
2urlpatterns = [
3 path('admin/', admin.site.urls),
4 path('books/', views.BookView.as_view()),
5 path('books/<int:pk>', views.BookDetailView.as_view()),
6]
2.2 常用字段
1BooleanField BooleanField()
2NullBooleanField NullBooleanField()
3CharField CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)
4EmailField EmailField(max_length=None, min_length=None, allow_blank=False)
5RegexField RegexField(regex, max_length=None, min_length=None, allow_blank=False)
6SlugField SlugField(maxlength=50, min_length=None, allow_blank=False) 正则字段,验证正则模式 [a-zA-Z0-9-]+
7URLField URLField(max_length=200, min_length=None, allow_blank=False)
8UUIDField UUIDField(format=’hex_verbose’) format: 1) 'hex_verbose' 如"5ce0e9a5-5ffa-654b-cee0-1238041fb31a" 2) 'hex' 如 "5ce0e9a55ffa654bcee01238041fb31a" 3)'int' - 如: "123456789012312313134124512351145145114" 4)'urn' 如: "urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"
9IPAddressField IPAddressField(protocol=’both’, unpack_ipv4=False, **options)
10IntegerField IntegerField(max_value=None, min_value=None)
11FloatField FloatField(max_value=None, min_value=None)
12DecimalField DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits: 最多位数 decimal_palces: 小数点位置
13DateTimeField DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None)
14DateField DateField(format=api_settings.DATE_FORMAT, input_formats=None)
15TimeField TimeField(format=api_settings.TIME_FORMAT, input_formats=None)
16DurationField DurationField()
17ChoiceField ChoiceField(choices) choices与Django的用法相同
18MultipleChoiceField MultipleChoiceField(choices)
19FileField FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
20ImageField ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
21ListField ListField(child=, min_length=None, max_length=None)
22DictField DictField(child=)
2.3 常用字段参数
1
2max_length 最大长度
3min_lenght 最小长度
4
5
6allow_blank 是否允许为空
7trim_whitespace 是否截断空白字符
8
9max_value 最小值
10min_value 最大值
11
12
13
14
15参数名称 说明
16
17read_only 表明该字段仅用于序列化输出,默认False
18write_only 表明该字段仅用于反序列化输入,默认False
19
20
21
22required 表明该字段在反序列化时必须输入,默认True
23default 反序列化时使用的默认值
24allow_null 表明该字段是否允许传入None,默认False
25validators 该字段使用的验证器
26error_messages 包含错误编号与错误信息的字典
3 序列化器的反序列化
3.1 基本使用
1 def post(self, request, *args, **kwargs):
2
3
4
5
6
7
8 ser = BookSerializer(data=request.data)
9
10 if ser.is_valid():
11 ser.save()
12 return Response(ser.data)
13 else:
14 return Response(ser.errors)
1 def put(self, request, pk):
2 book = Book.objects.filter(pk=pk).first()
3
4 ser = BookSerializer(instance=book, data=request.data)
5
6 if ser.is_valid():
7 ser.save()
8 return Response(ser.data)
3.2 数据校验
1
2title = serializers.CharField(max_length=8, min_length=3)
3
4
5
6 def validate_title(self, item):
7 print(item)
8
9 if item.startswith('sb'):
10 raise ValidationError('不能以sb开头')
11
12 return item
13
14 def validate(self, attrs):
15
16 if attrs.get('title') == attrs.get('publish'):
17 raise ValidationError('标题和出版社不能一样')
18
19 return attrs
4 模型类序列化器ModelSerializer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39class BookModelSerializer(serializers.ModelSerializer):
40
41 class Meta:
42 model = Book
43 fields = ['title', 'price', 'id', 'publish']
44
45
46
47
48
49
50
51
52
53 extra_kwargs = {
54 'title': {'read_only': True},
55
56 }