1 多表关联的序列化和反序列化
1多表关联的序列化和反序列化的三种方式
2
3
4
5
6
7
8
9
10
11 def get_publish(self):
12 return {"publish_name":self.publish.name,"addr":self.publish.addr}
13
14 def get_author(self):
15 l=[]
16 author_list = self.author.all()
17 for author_obj in author_list:
18 l.append({'name':author_obj.name})
19 return l
20
21
22class Book_Serializer(serializers.ModelSerializer):
23 class Meta:
24 model = Books
25 fields = ['id','title', 'price', 'publish', 'author','get_publish','get_author']
26 extra_kwargs = {'publish': {'write_only': True},
27 'author': {'write_only': True},
28 'publish_name': {'read_only': True},
29 'addr': {'read_only': True},
30 'name': {'read_only': True},
31
32 }
33
34
35
36class Book_Serializer(serializers.ModelSerializer):
37 class Meta:
38 model = Books
39 fields = ['id','title', 'price', 'publish', 'author','publish_parmer','author_parmer']
40 extra_kwargs = {'publish': {'write_only': True},
41 'author': {'write_only': True},
42
43
44
45
46 }
47 publish_parmer = serializers.SerializerMethodField(read_only=True)
48 author_parmer = serializers.SerializerMethodField(read_only=True)
49
50 def get_publish_parmer(self,obj):
51 return {'name':obj.publish.name,'addr':obj.publish.addr}
52
53 def get_author_parmer(self,obj):
54 author_list = obj.author.all()
55 l = []
56 for author_obj in author_list:
57 l.append({'name':author_obj.name})
58 return l
59
60
61from rest_framework import serializers
62from .models import Publish, Books, Author
63
64class AutorSerializer(serializers.ModelSerializer):
65 class Meta:
66 model = Author
67 fields = '__all__'
68
69
70class MySerializer(serializers.ModelSerializer):
71 class Meta:
72 model = Publish
73 fields = '__all__'
74
75
76class Book_Serializer(serializers.ModelSerializer):
77 class Meta:
78 model = Books
79 fields = ['id','title', 'price', 'publish', 'author']
80 extra_kwargs = {'publish': {'write_only': True},
81 'author': {'write_only': True},
82
83
84
85
86 }
87 publish = MySerializer()
88 author = AutorSerializer(many=True)
2 请求与响应
2.1 Request
1
2request.data
3request.query_params # 相当于request.GET
4request._request 原来的request
5request.method --->就是使用了原来的request的method 通过重写 __getattr__魔法方法实现的(点拦截)
6'''
7__getattr__ 方法,使用对象点属性,属性不存在触发
8'''
9
10
11'''
12django中不能处理json格式数据,request.body
13'''
14
15
16
17
18REST_FRAMEWORK = {
19
20 'DEFAULT_PARSER_CLASSES': (
21 'rest_framework.parsers.JSONParser',
22
23
24 )
25}
26
27
28class PublishView(APIView):
29 parser_classes = [FormParser,]
30
31
32
2.1 响应 Response
1
2data:返回给前端的数据,可以是字典,列表,字符串
3status:响应状态码,1xx 2xx 3xx 4xx 5xx
4template_name : 不用,替换模板
5headers=None :响应头
6
7
8
9
10REST_FRAMEWORK = {
11
12 'DEFAULT_RENDERER_CLASSES': (
13 'rest_framework.renderers.JSONRenderer',
14
15 )
16}
17
18
19class PublishView(APIView):
20 renderer_classes = [JSONRenderer,]
21
22
23
3 视图组件(重点)
3.1 两个视图基类
1
2from rest_framework.views import APIView
3from rest_framework.generics import GenericAPIView
4'''
5# 类属性
6queryset = None # 所有数据
7serializer_class = None # 序列化的类
8lookup_field = 'pk' # 查询单条转换器的字段
9
10# 三个方法
11self.get_queryset() # 获取所有数据
12self.get_serializer # 获取序列化类
13self.get_object() # 获取单条
14'''
15
16from rest_framework.mixins import RetrieveModelMixin,ListModelMixin,CreateModelMixin
17class PublishView(GenericAPIView):
18 queryset = Publish.objects.all()
19 serializer_class = PublishSerializer
20
21
22 def get(self, request):
23 obj = self.get_queryset()
24 ser = self.get_serializer(instance=obj, many=True)
25 return Response(data=ser.data)
26
27 def post(self, request):
28 ser = self.get_serializer(data=request.data)
29 if ser.is_valid():
30 ser.save()
31 return Response(ser.data)
32 else:
33 return Response(ser.errors)
34
35
36
37class PublishDetailView(GenericAPIView):
38 queryset = Publish.objects.all()
39 serializer_class = PublishSerializer
40 def get(self, request, pk):
41 obj = self.get_object()
42 ser = PublishSerializer(instance=obj)
43 return Response(data=ser.data)
44
45 def put(self, request, pk):
46 obj = self.get_object()
47
48 ser = self.get_serializer(data=request.data, instance=obj)
49 if ser.is_valid():
50 ser.save()
51 return Response(ser.data)
52 else:
53 return Response(ser.errors)
54
55 def delete(self, request, pk):
56 res = self.get_object().delete()
57 print(res)
58 if res[0] >= 1:
59 return Response()
60 else:
61 return Response('要删除的数据不存在')
django2版本,建立外键关系,必须要加on_delete参数
1建立一对多外键
2on_delete=models.CASCADE
3 models.DO_NOTHING
4 models.SET_DEFAULT
5 models.SET_NULL
6 models.SET