首页 > 其他分享 >视图类

视图类

时间:2022-12-08 21:58:43浏览次数:37  
标签:ser get self request 视图 book class

视图

目录

#两个视图基类
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__'
  • urls.py
from django.urls import path, re_path
from App3 import views

urlpatterns = [

    

   


]

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个视图扩展类写的接口

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'})),

标签:ser,get,self,request,视图,book,class
From: https://www.cnblogs.com/zaosong/p/16967444.html

相关文章

  • DRF的视图与路由集Routers
    一视图DjangoRESTframwork提供的视图的主要作用:控制序列化器的执行(检验、保存、转换数据)控制数据库模型的操作一普通视图APIView一两个视图基类1 APIVi......
  • 记录一次物化视图解决视图查询慢问题
    涉及一个视图优化,记录如下,会有相应时间的数据延迟。CREATEMATERIALIZEDVIEWPU_VIEW_STOREREQBUILDIMMEDIATEREFRESHFORCEONDEMANDSTARTWITHSYSDATENEXTSY......
  • 视图
         ......
  • Rup架构视图
    RUP中有四种软件视图,这里复习一下,并根据资料整理一下。.软件的质量特性分为功能性需求和非功能性需求。功能需求就是"软件有什么用,软件需要做什么"......
  • Flutter 陈航 09-视图渲染 三棵树 Widget
    本文地址目录目录目录09|Widget,构建Flutter界面的基石视图渲染过程WidgetElementRenderObjectRenderObjectWidget介绍Element的创建RenderObject的创建与更新案......
  • MySQL进阶实战6,缓存表、视图、计数器表
    一、缓存表和汇总表有时提升性能最好的方法是在同一张表中保存衍生的冗余数据,有时候还需要创建一张完全独立的汇总表或缓存表。缓存表用来存储那些获取很简单,但速度较慢......
  • DRF-视图
    DRF视图类中除了APIView类,还有一个GenericAPIView类。GenericAPIView类主要给我们提供了2个属性,3个方法。属性:queryset:要序列化的数据serializer_class:序列化类 方法......
  • mysql高阶语句+视图
    一,高阶语句1.select:显示表格中一个或数个栏位的所有资料格式:SELECT"栏位"FROM"表名";2.where:条件查询格式:SELECT"栏位"FROM"表名"WHERE"条件";嵌套/多条件,......
  • 报名啦!一起学习《多视图几何》、深度学习SLAM、GTSAM库、DSO、SVO Pro
    以下内容来自从零开始机器人SLAM知识星球每日更新内容点击领取学习资料→机器人SLAM学习资料大礼包原文链接:【https://mp.weixin.qq.com/s/BgWuX86veLs3mth0gANY5g】......
  • mysql索引,事务,视图,存储过程,存储引擎
    一,索引1.概念索引:提供指向存储在表的指定列中的数据值的指针,然后根据指定的排序顺序对这些指针排序。数据库使用索引以找到特定值,然后顺指针找到包含该值的行。索引就......