两个视图基类 快速实现publish的5个接口 9个视图子类
1 两个视图基类# APIView--->之前一直在用---》drf提供的最顶层的父类---》以后所有视图类,都继承自它
# GenericAPIView--》继承自APIView--》封装1.1 继承APIView+序列化类+Response写接口
urls.py--子路由--app01--urls.py
from django.contrib import admin
from django.urls import path,include
from app01 import views
urlpatterns = [
path('books/',views.BookView.as_view()),
path('books/<int:pk>/',views.BookDetaiView.as_view())
]序列化类
serializer.py
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model=Book
# 'publish', 'authors'反序列化
fields=['id','name','price','publish','authors','author_list','publish_detail']
extra_kwars={
'publish':{'weite_only':True},
'authors':{'weite_only':True},
'author_list':{'read_only':True},
'publish_detail':{'read_only':True},
}表模型
from django.db import models
# Create your models here.
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视图类
from .serializer import BookSerializer
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from .models import Book
from rest_framework.response import Response
class BookView(APIView):
def get(self, request):
booklist = Book.objects.all()
ser = BookSerializer(instance=booklist, 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 BookDetaiView(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')).first()
return Response('')1.2 继承GenericAPIView+序列化类+Response写接口
#第二层继承GenericAPIView+序列化类+Response写接口
from rest_framework.generics import GenericAPIView
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 BookDetaiView(GenericAPIView):
# 先配置两个类属性
queryset = Book.objects.all()
serializer_class = BookSerializer
def put(self, request, *args, **kwargs):
# book = Book.objects.filter(pk=kwargs.get('pk')).first()
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):
# book = Book.objects.filter(pk=kwargs.get('pk')).first()
obj=self.get_object()
ser = self.get_serializer(instance=obj)
return Response(ser.data)
def delete(self, request, *args, **kwargs):
# Book.objects.filter(pk=kwargs.get('pk')).first()
self.get_object().delete()
return Response('')快速实现publish的5个接口
只需要修改视图类上的两个类属性即可,其他的不用动
urls.py
from django.contrib import admin
from django.urls import path,include
from app01 import views
urlpatterns = [
#path('books/',views.BookView.as_view()),
#path('books/<int:pk>/',views.BookDetaiView.as_view()),
path('publish/',views.PublishView.as_view()),
path('publish/<int:pk>/',views.PublishDetaiView.as_view())
]views.py
#快速实现publish的5个接口
from .models import Publish
from .serializer import PublishSerializer
class PublishView(GenericAPIView):
# 先配置两个类属性
#用的话必须写
queryset =Publish.objects.all()
serializer_class = PublishSerializer
def get(self, request):
# object_list = self.queryset.all()# 获取所有要序列化的数据
# #1 写成方法的目的--》调用all()
# #2 子类可以重写这个方法--》返回什么,待序列化的数据就是什么
# object_list = self.get_queryset()# 获取所有要序列化的数据
object_list = self.get_queryset()#获取所有要序列化的数据
ser = self.get_serializer(instance=object_list, many=True)#获取序列化类
# 本质就是---》 self.serializer_class(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 PublishDetaiView(GenericAPIView):
# 先配置两个类属性
queryset = Publish.objects.all()
serializer_class = PublishSerializer
def put(self, request, *args, **kwargs):
# book = Book.objects.filter(pk=kwargs.get('pk')).first()
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):
# book = Book.objects.filter(pk=kwargs.get('pk')).first()
obj=self.get_object()
ser = self.get_serializer(instance=obj)
return Response(ser.data)
def delete(self, request, *args, **kwargs):
# Book.objects.filter(pk=kwargs.get('pk')).first()
self.get_object().delete()
return Response('')serializer.py
class PublishSerializer(serializers.ModelSerializer):
class Meta:
model = Publish
fields = "__all__"继承GenericAPIView的写法
-1 在类中,写两个类属性:所有数据,序列化类
queryset = Book.objects.all()
serializer_class = BookSerializer
-2 获取所有要序列化的数据
self.get_queryset()
-3 获取序列化类
self.get_serializer(参数跟之前一样)
-4 获取单挑
self.get_object()GenericAPIView源码分析
-1 继承了APIView
-2 有些类属性--》目前只记住两个queryset,serializer_class
queryset # 要序列化的所有数据
serializer_class# 序列化类
lookup_field = 'pk' # 查询单条,前端传入的参数对应值【pk】,转换器
filter_backends# 后续要学的,过滤
pagination_class # 后续要学的,分页
-3 有些对象方法
-get_queryset: 返回待序列化的数据
1 调用 .all
2 在子类中重写,控制要序列化的数据
-get_serializer: 返回 序列化类以后用它
-本质就是---》 self.serializer_class(instance=object_list, many=True)
-内部调用了:self.get_serializer_class
-后期在子类中重写get_serializer_class,返回什么序列化类,以后就以哪个序列化类做序列化
- get_serializer_class 它是用来重写的
def get_serializer_class(self):
if self.request.method=='GET':
return '序列化的类'
else:
return '反序列化的类'
-get_object 获取单条---》根据它:lookup_field 获取
第三层:继承 GenericAPIView+5个视图扩展类+序列化类+Response
5个视图扩展类(不是视图类--》没有继承APIView及其子类,不能单独用,需要配合GenericAPIView)---》每个分别写的5个接口中得某一个方法
from rest_framework.mixins import CreateModelMixin, ListModelMixin, RetrieveModelMixin, UpdateModelMixin, \
DestroyModelMixin
#CreateModelMixin 新增
#ListModelMixin查询所有
#RetrieveModelMixin查询单条
#UpdateModelMixin修改
# DestroyModelMixin销毁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):
# object_list = self.get_queryset()#获取所有要序列化的数据
# ser = self.get_serializer(instance=object_list, many=True)#获取序列化类
# return Response(ser.data)
return super().list(request)
def post(self, request):
# 做保存,加了这一句---》目的是:子类可以重写,增强扩展性
# self.perform_create(serializer)
return super().list(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个视图子类
第四层:9个视图子类---》视图类
#CreateModelMixin 新增
#ListModelMixin查询所有
# ListCreateAPIView 新增+查询所有
#RetrieveModelMixin查询单条
#UpdateModelMixin修改
# DestroyModelMixin销毁
# RetrieveUpdateDestroyAPIView查询单条+修改+销毁
# RetrieveDestroyAPIView查询单条+ 销毁
# RetrieveUpdateAPIView查询单条+修改
# CreateAPIView继承了 GenericAPIView, CreateModelMixin,写了post方法
from rest_framework.generics import CreateAPIView,ListAPIView,ListCreateAPIView
from rest_framework.generics import RetrieveAPIView,DestroyAPIView,UpdateAPIView,RetrieveUpdateDestroyAPIView
from rest_framework.generics import RetrieveDestroyAPIView,RetrieveUpdateAPIView
#实现
class BookView(ListCreateAPIView):
# 先配置两个类属性
#用的话必须写
queryset =Book.objects.all()
serializer_class = BookSerializer
class BookDetailView(RetrieveUpdateDestroyAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
# 实现新增,查所有和查询一条
# class BookView(ListCreateAPIView):
# # 配置两个类属性
# queryset = Book.objects.all()
# serializer_class = BookSerializer
#
#
# class BookDetailView(RetrieveAPIView):
# queryset = Book.objects.all()
# serializer_class = BookSerializer
来源:https://www.cnblogs.com/zhangfanshixiaobai/p/17927061.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页:
[1]