drf知识--05
两个视图基类
# APIView:之前一直在用---》drf提供的最顶层的父类---》以后所有视图类,都继承自它
# GenericAPIView:继承自APIView--》封装
继承APIView+序列化类+Response写接口
# urls.py--总路由 from django.contrib import admin from django.urls import path,include from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('app/',include('app01.urls'))] # urls.py--子路由app01 from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('books/', views.BookView.as_view()), path('books/<int:pk>', views.BookDetailView.as_view()),]
# 序列化类 from rest_framework import serializers from .models import Book class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ['id', 'name', 'price', 'publish', 'authors', 'publish_detail', 'author_list'] extra_kwargs = { 'publish': {'write_only': True}, 'authors': {'write_only': True}, 'publish_detail': {'read_only': True}, 'author_list': {'read_only': True}, }
# models.py from django.db import models class Book(models.Model): name = models.CharField(max_length=32) price = models.DecimalField(max_digits=5, decimal_places=2) publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE) authors = models.ManyToManyField(to='Author') @property def publish_detail(self): return {'name': self.publish.name, 'city': self.publish.city} @property def author_list(self): l = [] for author in self.authors.all(): l.append({'name': author.name, 'age': author.age}) return l def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=32) age = models.IntegerField() author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE) def __str__(self): return self.name class AuthorDetail(models.Model): telephone = models.BigIntegerField() birthday = models.DateField() addr = models.CharField(max_length=64) class Publish(models.Model): name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.name class Meta: verbose_name = '出版社' verbose_name_plural = verbose_name
# views.py class BookView(APIView): def get(self, request): book_list = Book.objects.all() ser = BookSerializer(instance=book_list, many=True) return Response(ser.data) def post(self, request): ser = BookSerializer(data=request.data) if ser.is_valid(): ser.save() return Response(ser.data) else: return Response(ser.errors) class BookDetailView(APIView): def put(self, request, *args, **kwargs): book = Book.objects.filter(pk=kwargs.get('pk')).first() ser = BookSerializer(instance=book, data=request.data) if ser.is_valid(): ser.save() return Response(ser.data) else: return Response(ser.errors) def get(self, request, *args, **kwargs): book = Book.objects.filter(pk=kwargs.get('pk')).first() ser = BookSerializer(instance=book) return Response(ser.data) def delete(self, request, *args, **kwargs): Book.objects.filter(pk=kwargs.get('pk')).delete() return Response('')
继承GenericAPIView+序列化类+Response写接口
# 继承GenericAPIView的写法
?? ?-1 在类中,写两个类属性:所有数据,序列化类
? ? ? ? queryset = Book.objects.all()
? ? ?? ?serializer_class = BookSerializer
? ? -2 获取所有要序列化的数据:
? ? ?? ?self.get_queryset()
? ? -3 获取序列化类
? ? ?? ?self.get_serializer(参数跟之前一样)
? ? -4 获取单挑
? ? ?? ?self.get_object()
# 如果想快速写出Publish的5个接口,只需要修改视图类上的两个类属性即可
?? ? ? ?queryset = Publish.objects.all()
? ? ?? ?serializer_class = PublishSerializer
# GenericAPIView源码分析:
? ?1 继承了APIView
? ?2 有些类属性--》目前只记住两个queryset,serializer_classqueryset ? ? ? ? # 要序列化的所有数据 serializer_class ?# 序列化类 lookup_field = 'pk' # 查询单条,前端传入的参数对应值【pk】,转换器 filter_backends ? # 后续要学的,过滤 pagination_class # 后续要学的,分页
? ?3 有些对象方法
get_queryset: 返回待序列化的数据
? ? ? 调用 .all ,在子类中重写,控制要序列化的数据
get_serializer: 返回 序列化类 ?以后用它
? ? ??本质就是 self.serializer_class(instance=object_list, many=True)?
? ? ? 内部调用了:self.get_serializer_class
? ? ? 后期可在子类中重写get_serializer_class,返回什么序列化类就以哪个序列化类做序列化get_object:获取单条,根据它:lookup_field ? 获取
get_serializer_class 它是用来重写的 def get_serializer_class(self): ? ? ? if self.request.method=='GET': ? ? ? ? ? return '序列化的类' ? ? ? else: ? ? ? ? ? return '反序列化的类'
#?对象属性查找顺序:
? ? ? ? ? ? ?在类中定义了属性,对象中放入了属性
?????????????self.属性 ?用的对象自己的,如果对象中没放:self.属性用了类的# 总结:
# urls.py urlpatterns = [ path('books/', views.BookView.as_view()), path('books/<int:pk>', views.BookDetailView.as_view()), path('publish/', views.PublishView.as_view()), path('publish/<int:pk>', views.PublishDetailView.as_view()), ]
# serializer.py class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ['id', 'name', 'price', 'publish', 'authors', 'publish_detail', 'author_list'] extra_kwargs = { 'publish': {'write_only': True}, 'authors': {'write_only': True}, 'publish_detail': {'read_only': True}, 'author_list': {'read_only': True}, } class PublishSerializer(serializers.ModelSerializer): class Meta: model = Publish fields = "__all__"
# views.py from rest_framework.generics import GenericAPIView from .models import Publish from .serializer import PublishSerializer class BookView(GenericAPIView): queryset = Book.objects.all() serializer_class = BookSerializer def get(self, request): object_list = self.get_queryset() # 获取所有要序列化的数据 ser = self.get_serializer(instance=object_list, many=True) # 获取序列化类 return Response(ser.data) def post(self, request): ser = self.get_serializer(data=request.data) if ser.is_valid(): ser.save() return Response(ser.data) else: return Response(ser.errors) class BookDetailView(GenericAPIView): queryset = Book.objects.all() serializer_class = BookSerializer def put(self, request, *args, **kwargs): obj = self.get_object() # 获取单挑---》内部就是按pk从request中取,取出pk对应的值,查询的 ser = self.get_serializer(instance=obj, data=request.data) if ser.is_valid(): ser.save() return Response(ser.data) else: return Response(ser.errors) def get(self, request, *args, **kwargs): obj = self.get_object() ser = self.get_serializer(instance=obj) return Response(ser.data) def delete(self, request, *args, **kwargs): self.get_object().delete() return Response('')
5个视图扩展类
# 继承 GenericAPIView+5个视图扩展类+序列化类+Response
# views.py from rest_framework.mixins import CreateModelMixin, ListModelMixin, RetrieveModelMixin, UpdateModelMixin, \ DestroyModelMixin class BookView(GenericAPIView, CreateModelMixin, ListModelMixin): queryset = Book.objects.all() serializer_class = BookSerializer def get(self, request): return super().list(request) def post(self, request): # 做保存,加了这一句---》目的是:子类可以重写,增强扩展性 # self.perform_create(serializer) return super().create(request) class BookDetailView(GenericAPIView, RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin): queryset = Book.objects.all() serializer_class = BookSerializer def put(self, request, *args, **kwargs): return super().update(request, *args, **kwargs) def get(self, request, *args, **kwargs): return super().retrieve(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return super().destroy(request, *args, **kwargs)
9个视图子类
# CreateAPIView继承了 GenericAPIView, CreateModelMixin,写了post方法
views.py from rest_framework.generics import CreateAPIView, ListAPIView from rest_framework.generics import RetrieveAPIView, DestroyAPIView, UpdateAPIView from rest_framework.generics import ListCreateAPIView from rest_framework.generics import RetrieveUpdateDestroyAPIView, RetrieveDestroyAPIView, RetrieveUpdateAPIView # from rest_framework.generics import DestroyUpdateAPIView # 一般不存在,所以就没有 # 实现新增,查所有和查询一条 class BookView(ListCreateAPIView): # 配置两个类属性 queryset = Book.objects.all() serializer_class = BookSerializer class BookDetailView(RetrieveAPIView): queryset = Book.objects.all() serializer_class = BookSerializer
视图集
# views.py from rest_framework.viewsets import ModelViewSet class BookView(ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer
urls.py path('books/', views.BookView.as_view({'get':'list','post':'create'})), path('books/<int:pk>', views.BookView.as_view({'get':'retrieve','put':'update','delete':'destroy'})),
今日思维导图:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!