目录
1.序列化many参数源码分析(了解)
2.局部全局钩子的源码分析(了解)
3.序列化对象.data
4.两个视图基类
5.五个视图扩展类
6.九个视图子类
7.视图集
8.GenericAPIView基类(初级方法)
9.GenericAPIView视图扩展类(中级方法)
10.GenericAPIView视图子类类 (高级方法)
11.GenericAPIView视图集类 (超级方法)
12.总结
1.序列化many参数源码分析(了解)
1 序列化类实例化的时候,传了many,序列化多条,不传,就序列化单条
#many=True,实例化得到的对象是ListSerializer
ser=serializer.BookModelSerializer(instance=qs,many=True)
print(type(ser))
#rest_framework.serializers.ListSerializer
# 列表中套了很多BookModelSerializer
#many=False,实例化得到的对象是BookModelSerializer
ser=serializer.BookModelSerializer(instance=book)
print(type(ser))
#app01.serializer.BookModelSerializer
类实例化:在执行__init__之前,先执行了__new__生成一个空对象(决定了是哪个类的对象)
在__new__中进行判断,如果many=True,就返回ListSerializer的对象
2.局部全局钩子的源码分析(了解)
is_valid()
判断_validated_data如果没有
执行了 self.run_validation(self.initial_data)
目前在BaseSerializer,如果按住ctrl点击,会直接进到它父类的run_validation,进到Field,不是真正执行的方法
我们需要从头找,实际上是Serializer类的run_validation
def run_validation(self, data=empty):
value = self.to_internal_value(data)#字段自己的校验和局部钩子
try:
self.run_validators(value)
value = self.validate(value) # 全局钩子
assert value is not None,
except (ValidationError, DjangoValidationError) as exc:
raise ValidationError(detail=as_serializer_error(exc))
return value
局部钩子是在 to_internal_value执行的
def to_internal_value(self, data):
for field in fields:
validate_method = getattr(self, 'validate_' + field.field_name, None)
if validate_method is not None:
validated_value = validate_method(validated_value)
##总结:
is_valid---》BaseSerializer的is_valid--》执行了self.run_validation(self.initial_data)---》Serializer的run_validation---》self.to_internal_value(data):局部钩子|||
value = self.validate(value) :全局钩子
self.to_internal_value(data):局部钩子----》getattr(self, 'validate_' + field.field_name, None)
3.序列化对象.data
序列化对象.data方法--调用父类data方法---调用对象自己的to_representation(自定义的序列化类无此方法,去父类找)
Serializer类里有to_representation方法,for循环执行attribute = field.get_attribute(instance)
再去Field类里去找get_attribute方法,self.source_attrs就是被切分的source,然后执行get_attribute方法,source_attrs
当参数传过去,判断是方法就加括号执行,是属性就把值取出来
4.两个视图基类
1 APIView
2 GenericAPIView(APIView):做了一些封装
-属性:
queryset
serializer_class
-方法:
get_queryset:获取qs数据
get_object:获取一条数据的对象
get_serializer:以后使用它来实例化得到ser对象
get_serializer_class:获取序列化类,注意跟上面区分
5.五个视图扩展类
# 5个视图扩展类(rest_framework.mixins)
CreateModelMixin:create方法创建一条
DestroyModelMixin:destory方法删除一条
ListModelMixin:list方法获取所有
RetrieveModelMixin:retrieve获取一条
UpdateModelMixin:update修改一条
6.九个视图子类
# 9个子类视图(rest_framework.generics)
1 ListAPIView (查所有)
2 RetrieveAPIView (查一个)
3 DestroyAPIView(删一个)
4 UpdateAPIView (改一个)
5 CreateAPIView (增一个)
6 ListCreateAPIView (查所有+增一个)
7 RetrieveDestroyAPIView (查一个+删一个)
8 RetrieveUpdateAPIView (查一个+改一个)
9 RetrieveUpdateDestroyAPIView (查一个+删一个+改一个)
CreateAPIView:继承CreateModelMixin,GenericAPIView,有post方法,新增数据
DestroyAPIView:继承DestroyModelMixin,GenericAPIView,有delete方法,删除数据
ListAPIView:继承ListModelMixin,GenericAPIView,有get方法获取所有
UpdateAPIView:继承UpdateModelMixin,GenericAPIView,有put和patch方法,修改数据
RetrieveAPIView:继承RetrieveModelMixin,GenericAPIView,有get方法,获取一条
ListCreateAPIView:继承ListModelMixin,CreateModelMixin,GenericAPIView,有get获取所有,post方法新增
RetrieveDestroyAPIView:继承RetrieveModelMixin,DestroyModelMixin,GenericAPIView,有get方法获取一条,delete方法删除
RetrieveUpdateAPIView:继承RetrieveModelMixin,UpdateModelMixin,GenericAPIView,有get获取一条,put,patch修改
RetrieveUpdateDestroyAPIView:继承RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIView,有get获取一条,put,patch修改,delete删除
7.视图集
ViewSetMixin:重写了as_view
ViewSet: 继承ViewSetMixin和APIView
GenericViewSet:继承ViewSetMixin, generics.GenericAPIView
ModelViewSet:继承mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,mixins.ListModelMixin,GenericViewSet
ReadOnlyModelViewSet:继承mixins.RetrieveModelMixin,mixins.ListModelMixin,GenericViewSet
8.GenericAPIView基类(初级方法)
8.1 视图
# 只需要修改定义方法的数据和类
class PublishViews(GenericAPIView):
queryset = models.Publish.objects.all() # 序列化的数据
serializer_class = serializer.PublishModelSerializer # 序列化的类
def get(self, request, *args, **kwargs):
response = {'status': 200, 'msg': '查询'}
try:
qs = self.get_queryset()
ser = self.get_serializer(instance=qs, many=True) # many全部
# return Response(ser.data)
# book.data字典加入到data列表里
response['data'] = ser.data
except Exception as e:
# 返回错误信息
response['msg'] = str(e)
return Response(response)
# 增加
def post(self, request, *args, **kwargs):
response = {'status': 200, 'msg': '新增'}
try:
ser = self.get_serializer(data=request.data)
if ser.is_valid():
ser.save()
response['data'] = ser.data
else:
response['msg'] = ser.errors
except Exception as e:
response['msg'] = str(e)
return Response(response)
class PublishViewsId(GenericAPIView):
queryset = models.Publish.objects.all() # 序列化的数据
serializer_class = serializer.PublishModelSerializer # 序列化的类
# 查询一个
def get(self, request, *args, **kwargs):
response = {'status': 200, 'msg': '成功'}
try:
# 取出id
obj = self.get_object()
# 序列化
ser = self.get_serializer(instance=obj)
# book.data字典加入到data列表里
response['data'] = ser.data
except Exception as e:
# 返回错误信息
response['msg'] = str(e)
return Response(response)
# 修改数据
def put(self, request, *args, **kwargs):
response = {'status': 200, 'msg': '成功'}
try:
# 取出id
obj = self.get_object()
# 拿到id号反序列化
ser = self.get_serializer(instance=obj, data=request.data)
# 校验
if ser.is_valid():
ser.save()
response['data'] = ser.data
else:
response['msg'] = ser.errors
except Exception as e:
# 返回错误信息
response['msg'] = str(e)
return Response(response)
# 删除
def delete(self, request, *args, **kwargs):
# 查询到id号
res = self.get_object().delete()
# 判断第一个删除
if res[0] > 0:
return Response('')
else:
return Response('删除的不存在')
8.2 序列化类
from rest_framework import serializers
from restful import models
# 继承ModelSerializer类
class PublishModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.Publish
# __all__ 查询所有
fields = '__all__'
8.3 路由
from restful import views
urlpatterns = [
path('publish/<int:pk>/', views.PublishViewsId.as_view()),
path('publish/', views.PublishViews.as_view()),
]
8.4 settings配置app(注意记得配置数据库也可以用自带sqllite3)
INSTALLED_APPS = [
'rest_framework'
]
8.5 models 表模型(注意迁移)
from django.db import models
class Book(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=5, decimal_places=2)
publish_date = models.DateField()
publish = models.ForeignKey(to='Publish', to_field='nid', on_delete=models.CASCADE)
authors = models.ManyToManyField(to='Author')
def __str__(self):
return self.name
class Author(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
age = models.IntegerField()
author_detail = models.OneToOneField(to='AuthorDatail', to_field='nid', unique=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
class AuthorDatail(models.Model):
nid = models.AutoField(primary_key=True)
telephone = models.BigIntegerField()
birthday = models.DateField()
addr = models.CharField(max_length=64)
def __str__(self):
return self.addr
class Publish(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
city = models.CharField(max_length=32)
email = models.EmailField()
def __str__(self):
return self.name
8.6 admin配置(注意创建用户 createsuperuser)
from django.contrib import admin
from restful import models
admin.site.register(models.Book)
admin.site.register(models.Author)
admin.site.register(models.AuthorDatail)
admin.site.register(models.Publish)
9.GenericAPIView视图扩展类(中级方法,其它序列化类路由配置同上)
from restful import models
from restful import serializer
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin,CreateModelMixin,UpdateModelMixin,DestroyModelMixin,RetrieveModelMixin
class PublishViews(GenericAPIView, ListModelMixin, CreateModelMixin):
queryset = models.Publish.objects.all() # 序列化的数据
serializer_class = serializer.PublishModelSerializer # 序列化的类
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
class PublishViewsId(GenericAPIView, RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin):
queryset = models.Publish.objects.all() # 序列化的数据
serializer_class = serializer.PublishModelSerializer # 序列化的类
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.delete(request, *args, **kwargs)
10.GenericAPIView视图子类类(高级方法,其它序列化类路由配置同上)
from rest_framework.generics import ListAPIView,CreateAPIView,RetrieveAPIView,UpdateAPIView,DestroyAPIView,
from rest_framework.generics import ListCreateAPIView,RetrieveUpdateAPIView,RetrieveDestroyAPIView,RetrieveUpdateDestroyAPIView
from restful import models
from restful import serializer
class PublishViews(ListCreateAPIView):
queryset = models.Publish.objects.all() # 序列化的数据
serializer_class = serializer.PublishModelSerializer # 序列化的类
class PublishViewsId(RetrieveUpdateDestroyAPIView):
queryset = models.Publish.objects.all() # 序列化的数据
serializer_class = serializer.PublishModelSerializer # 序列化的类
11.GenericAPIView视图集类 (超级方法,序列化类表模型配置同上)
11.1 视图
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet
from rest_framework.viewsets import ViewSet, GenericViewSet, ViewSetMixin
# ModelViewSet五个接口都有
# ReadOnlyModelViewSet 只有读的两个接口
class PublishViews(ModelViewSet):
queryset = models.Publish.objects.all() # 序列化的数据
serializer_class = serializer.PublishModelSerializer # 序列化的类
11.2 路由
from restful import views
urlpatterns = [
path('publish/', views.PublishViews.as_view({'get':'list', 'post':'create'})),
path('publish/<int:pk>/', views.PublishViews.as_view({'get':'retrieve', 'put':'update', 'delete':'destroy'})),
]
12 总结
1 序列化器源码
-many参数控制,在__new__中控制了对象的生成
-局部和全局钩子源码:is_valid--》找self.方法一定要从根上找
-source参数是如何执行的:‘publish.name’,'方法'
2 视图:
-2个视图基类
-5个视图扩展类
-9个视图子类
-视图集
-ViewSetMixin
-ViewSet, GenericViewSet
-ModelViewSet, ReadOnlyModelViewSet
3 视图类的继承原则
-如果不涉及数据库操作:继承APIView
-如果想让路由可以映射:继承ViewSetMixin
-如果不涉及数据库操作,又要让路由可以映射:继承ViewSet
-比如发邮件接口,发短信接口
-如果涉及到数据库操作:继承GenericAPIView
-如果想让路由可以映射:继承ViewSetMixin
-如果涉及数据库操作,又要让路由可以映射:继承GenericViewSet
-如果涉及数据库操作,又要让路由可以映射,还要能新增:继承GenericViewSet+CreateModelMixin或者继承ViewSetMixin+CreateAPIView
-如果只涉及到数据库操作和新增:继承CreateAPIView
-路由有映射,数据库操作,3个接口(查一个,删一个改一个)
4 ViewSetMixin:路由的写法就特殊了
5 类实例化,先执行了元类的__call__:调用了这个类的__new__,生成一个空对象,调用了类的__init__,完成了对象的初始化
6 对象()---->会触发类的 __call__
7 类()----->会触发类的类(元类)的__call__