视图
目录
视图
#两个视图基类
APIView
GenericAPIView(继承APIView),涉及到数据库和序列化类的操作,尽量用GenericAPIView
先写模型类和序列化类,然后配置路由
- models.py
from django.db import models
# Create your models here.
class Book(models.Model):
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=8, decimal_places=3)
publish = models.CharField(max_length=32)
- ser.py
# -*- coding: UTF-8 -*-
# @Date :2022/12/8 11:18
from rest_framework import serializers
from App3.models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
1、基于APIView写5个接口
from rest_framework.views import APIView
from App3.ser import BookSerializer
from App3.models import Book
from rest_framework.response import Response
class BookView(APIView):
# 获取所有
def get(self, request):
book_list_obj = Book.objects.all()
book_ser = BookSerializer(book_list_obj, many=True)
return Response(book_ser.data)
def post(self, request):
book_ser = BookSerializer(data=request.data)
if book_ser.is_valid():
book_ser.save()
return Response(book_ser.data)
else:
return Response({'status': 101, 'msg': '校验失败'})
class BookDetailView(APIView):
# 获取单条
def get(self, request, pk):
book_obj = Book.objects.filter(pk=pk).first()
book_ser = BookSerializer(book_obj)
return Response(book_ser.data)
def put(self, request, pk):
book_obj = Book.objects.filter(pk=pk).first()
book_ser = BookSerializer(instance=book_obj, data=request.data)
if book_ser.is_valid():
book_ser.save()
return Response(book_ser.data)
else:
return Response({'status': 101, 'msg': '校验失败'})
def delete(self, request, pk):
book_obj = Book.objects.filter(pk=pk).delete()
return Response({'status': 100, 'msg': '删除成功'})
"""基于APIView的路由配置"""
path('books/', views.BookView.as_view()),
re_path('book/(?P<pk>\d+)', views.BookDetailView.as_view()),
2、基于GenericAPIView写5个接口
"""基于GenericAPIView写的5个接口"""
class BookGenericView(GenericAPIView):
# queryset要传QuerySet对象
# serializer_class要传使用哪个序列化类来序列化数据
queryset = Book.objects.all()
serializer_class = BookSerializer
# 获取所有
def get(self, request):
book_list_obj = self.get_queryset()
# book_ser=self.get_serializer_class()(book_list_obj,many=True)
book_ser = self.get_serializer(book_list_obj,many=True)
return Response(book_ser.data)
def post(self, request):
# book_ser = self.get_serializer_class()(data=request.data)
book_ser = self.get_serializer(data=request.data)
if book_ser.is_valid():
book_ser.save()
return Response(book_ser.data)
else:
return Response({'status': 101, 'msg': '校验失败'})
class BookGenericDetailView(GenericAPIView):
queryset = Book.objects
serializer_class = BookSerializer
# 获取单条
def get(self, request, pk):
book_obj = self.get_object()
# book_ser=self.get_serializer_class()(book_obj)
book_ser = self.get_serializer(book_obj)
return Response(book_ser.data)
def put(self, request, pk):
book_obj = self.get_object()
# book_ser = self.get_serializer_class()(instance=book_obj,data=request.data)
book_ser = self.get_serializer(instance=book_obj,data=request.data)
if book_ser.is_valid():
book_ser.save()
return Response(book_ser.data)
else:
return Response({'status': 101, 'msg': '校验失败'})
def delete(self, request, pk):
book_obj = self.get_object().delete()
return Response({'status': 100, 'msg': '删除成功'})
"""基于GenericAPIView的路由配置"""
path('books2/', views.BookGenericView.as_view()),
re_path('book2/(?P<pk>\d+)', views.BookGenericDetailView.as_view()),
3、基于GenericAPIView和5个视图扩展类写的接口
父类都是object
ListModelMixin,
CreateModelMixin,
UpdateModelMixin,
DestroyModelMixin,
RetrieveModelMixin
from rest_framework.mixins import ListModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin, RetrieveModelMixin
# views.py
class Book3View(GenericAPIView, ListModelMixin, CreateModelMixin):
queryset = Book.objects
serializer_class = BookSerializer
def get(self, request):
return self.list(request)
def post(self, request):
return self.create(request)
class Book3DetailView(GenericAPIView, RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin):
queryset = Book.objects
serializer_class = BookSerializer
def get(self, request, pk):
return self.retrieve(request, pk)
def put(self, request, pk):
return self.update(request, pk)
def delete(self, request, pk):
return self.destroy(request, pk)
#urls.py
path('books3/', views.Book3View.as_view()),
re_path('books3/(?P<pk>\d+)', views.Book3DetailView.as_view()),
4、基于GenericAPIView写的9个视图子类
# 继承了GenericAPIView+一个或两者或三个试图扩展类
CreateAPIView
ListAPIView
RetrieveAPIView
DestroyAPIView
UpdateAPIView
ListCreateAPIView
RetrieveUpdateAPIView
RetrieveDestroyAPIView
RetrieveUpdateDestroyAPIView
#views.py
from rest_framework.generics import CreateAPIView, ListAPIView, UpdateAPIView, RetrieveAPIView, DestroyAPIView,ListCreateAPIView,RetrieveUpdateDestroyAPIView,RetrieveUpdateAPIView,RetrieveDestroyAPIView
class Book4View(ListAPIView, CreateAPIView):
queryset = Book.objects
serializer_class = BookSerializer
class Book4DetailView(UpdateAPIView,RetrieveAPIView,DestroyAPIView):
queryset = Book.objects
serializer_class = BookSerializer
#urls.py
path('books4/', views.Book4View.as_view()),
re_path('books4/(?P<pk>\d+)', views.Book4DetailView.as_view()),
5、使用ModelViewSet编写五个接口
#views.py
from rest_framework.viewsets import ModelViewSet
class Book5View(ModelViewSet):
queryset = Book.objects
serializer_class = BookSerializer
#urls.py
path('books5/', views.Book5View.as_view(actions={'get': 'list', 'post': 'create'})),
# 当路径匹配,又是get请求,会执行Book5View的list方法
re_path('books5/(?P<pk>\d+)',views.Book5View.as_view(actions={'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
6、ViewSetMixin源码分析
#重写了as_view()
# 路由中只要配置了对应关系,比如:{'get':'list'},当get请求来,就会执行list方法
def view(request, *args, **kwargs):
self = cls(**initkwargs)
if 'get' in actions and 'head' not in actions:
actions['head'] = actions['get']
self.action_map = actions
for method, action in actions.items():
#method:get
#action:list,
handler = getattr(self, action)
#执行完上一句,handler就变成了list的内存地址
setattr(self, method, handler)
#执行完上一句,对象.get=list
#for循环完毕,对象,get:list 对象.post:create
self.request = request
self.args = args
self.kwargs = kwargs
return self.dispatch(request, *args, **kwargs)
7、继承ViewSetMixin的视图类
#继承ViewSetMixin的视图类,路由可以改写,视图类里的方法名字随意
#views.py
from rest_framework.viewsets import ViewSetMixin
class Book6View(ViewSetMixin, APIView): # ViewSetMinxin一定要放在APIView前,
"""继承的查找顺序:自己里面找,如果没有,先去第一个父类里找,再找第二个父类,"""
def get_all_book(self, request):
book_obj = Book.objects.all()
book_ser = BookSerializer(book_obj, many=True)
return Response(book_ser.data)
#urls.py
path('books6/', views.Book6View.as_view(actions={'get': 'get_all_book'})),
本文来自博客园,作者:ExpiredSaury,转载请注明原文链接:https://www.cnblogs.com/saury/p/16976681.html