首页 > 其他分享 >视图

视图

时间:2022-12-12 17:37:46浏览次数:45  
标签: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/16976681.html

相关文章

  • Django视图层
    视图层目录视图层1、三板斧2、JsonResponse对象3、form表单上传文件及后端如何操作4、request对象5、响应对象6、FBV与CBV视图响应的过程:当⽤户从浏览器发起⼀次请求时,......
  • 视图、索引和数据库表之间的关系
    1表数据库中的数据都存储在表中;表示物理存储的,真实存在的。2视图2.1视图的定义视图:视图本身就是一张虚拟表,其内容与真实表类似,包含一些列带有名称的列和行数据。......
  • Oracle数据库权限学习--表或者是视图不存在
    Oracle数据库权限学习--表或者是视图不存在摘要本文写于:12.1001:00巴西踢的太烂了帮同事看一下补丁执行报错的问题.问题原因很简单.user_all_table能够后去本用......
  • 在servlet配置的xml文件里面配置hander和handerAdapter以及视图解析器
    <!--配置HandlerMapping根据一个bean的name的属性,去寻找对应的Handler--><beanclass="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/><!--定......
  • 视图类
    视图目录视图1、基于APIView写5个接口2、基于GenericAPIView写5个接口3、基于GenericAPIView和5个视图扩展类写的接口4、基于GenericAPIView写的9个视图子类5、使用ModelV......
  • DRF的视图与路由集Routers
    一视图DjangoRESTframwork提供的视图的主要作用:控制序列化器的执行(检验、保存、转换数据)控制数据库模型的操作一普通视图APIView一两个视图基类1 APIVi......
  • 记录一次物化视图解决视图查询慢问题
    涉及一个视图优化,记录如下,会有相应时间的数据延迟。CREATEMATERIALIZEDVIEWPU_VIEW_STOREREQBUILDIMMEDIATEREFRESHFORCEONDEMANDSTARTWITHSYSDATENEXTSY......
  • 视图
         ......
  • Rup架构视图
    RUP中有四种软件视图,这里复习一下,并根据资料整理一下。.软件的质量特性分为功能性需求和非功能性需求。功能需求就是"软件有什么用,软件需要做什么"......
  • Flutter 陈航 09-视图渲染 三棵树 Widget
    本文地址目录目录目录09|Widget,构建Flutter界面的基石视图渲染过程WidgetElementRenderObjectRenderObjectWidget介绍Element的创建RenderObject的创建与更新案......