current position:Home>Django view

Django view

2022-01-31 21:14:16 Waiting for

This is my participation 11 The fourth of the yuegengwen challenge 16 God , Check out the activity details :2021 One last more challenge

One 、 brief introduction

django rest framework Brought us a lot of components , In addition to certification 、 jurisdiction 、 serialize ... One of the important components is the view , The general view is used with routing , This gives us a more flexible way to use it , For users, different views have different functions , In this way, we can customize our views according to our needs . The following is the portal of the official website :www.django-rest-framework.org/api-guide/v…

In the previous post , Due to mixed permissions 、 Certification, etc ( If you don't understand, please read the previous articles on the blog ), Not in this chapter , The following simple model is used to illustrate :

settings Register in django rest framework

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
    'rest_framework',
]
 Copy code 

models.py

from django.db import models

# Create your models here.
class UserInfo(models.Model):
    username = models.CharField(max_length=32,unique=True)
    password = models.CharField(max_length=64)
 Copy code 

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/v1/users', views.UerView.as_view()),  
]
 Copy code 

Two 、 Various views are used

1.APIView

This view is the most basic view , How to use... Has been described in previous chapters

2.GenericAPIView

This view encapsulates some static fields for us , Used to call other components , Example ( Please refer to the notes for explanation ):

from django.shortcuts import render

# Create your views here.

from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from rest_framework import serializers
from rest_framework import pagination
from app01 import models

class Userserializer(serializers.ModelSerializer):   # Serialize class definitions , The previous chapter has described 
    class Meta:
        model = models.UserInfo
        fields = '__all__'  # Serialize fields 

class Mypagination(pagination.PageNumberPagination):  #  Paging class definition , The previous chapters have also introduced 
    """ Custom paging """
    page_size=2  # By default, the number of displays per page is configured 
    page_query_param = 'p' #  Page parameters key, The default is page
    page_size_query_param='size'  #  Specify the number of displays per page parameter 
    max_page_size=4 #  Maximum number of displays per page , Use the above configuration , Can support each page to display 2~4 Data 

class UerView(GenericAPIView):            # View 
    queryset = models.UserInfo.objects.all()  # Data queryset
    serializer_class = Userserializer         #  Serialization classes use 
    permission_classes = []                   #  Permission authentication , There is no certification here , The previous chapter also introduces the authority 
    pagination_class = Mypagination # Paging class , The previous chapters have also introduced 
    def get(self,*args,**kwargs):
        roles=self.get_queryset()  #  obtain queryset, Actually take queryset, That is to say models.UserInfo.objects.all()
        page_res=self.paginate_queryset(queryset=roles)  # Paging results 
        res=self.get_serializer(instance=page_res,many=True)  # serialize 
        return Response(res.data)  # Return results 
 Copy code 

visit http://127.0.0.1:8000/api/v1/users , The results are as follows :

3.GenericViewSet

This view class needs to be used with routing , The modified urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
   # url(r'^api/v1/users', views.UserView.as_view()),
    url(r'^api/v2/users', views.UserView.as_view({'get':'show','post':'create'})), # rewrite as_view Method , And map the request method 
]
 Copy code 

views.py

from django.shortcuts import render

# Create your views here.

from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from rest_framework import serializers
from rest_framework import pagination
from rest_framework.viewsets import GenericViewSet
from app01 import models

class Userserializer(serializers.ModelSerializer):   # Serialize class definitions , The previous chapter has described 
    class Meta:
        model = models.UserInfo
        fields = '__all__'  # Serialize fields 

class Mypagination(pagination.PageNumberPagination):  #  Paging class definition , The previous chapters have also introduced 
    """ Custom paging """
    page_size=2  # By default, the number of displays per page is configured 
    page_query_param = 'p' #  Page parameters key, The default is page
    page_size_query_param='size'  #  Specify the number of displays per page parameter 
    max_page_size=4 #  Maximum number of displays per page , Use the above configuration , Can support each page to display 2~4 Data 

class UserView(GenericViewSet):            # View 
    queryset = models.UserInfo.objects.all()  # Data queryset
    serializer_class = Userserializer         #  Serialization classes use 
    permission_classes = []                   #  Permission authentication , There is no certification here , The previous chapter also introduces the authority 
    pagination_class = Mypagination # Paging class , The previous chapters have also introduced 
    def show(self,*args,**kwargs):  # And url The method names mapped in are the same 
        roles=self.get_queryset()  #  obtain queryset, Actually take queryset, That is to say models.UserInfo.objects.all()
        page_res=self.paginate_queryset(queryset=roles)  # Paging results 
        res=self.get_serializer(instance=page_res,many=True)  # serialize 
        return Response(res.data)  # Return results 

    def create(self,*args,**kwargs):
        pass
 Copy code 

visit http://127.0.0.1:8000/api/v2/users , The result is the same as the above result, as shown in figure :

4.ModelViewSet

modelViewSet Inherited mixins.CreateModelMixin、mixins.RetrieveModelMixin、mixins.UpdateModelMixin、mixins.DestroyModelMixin、mixins.ListModelMixin、GenericViewSet So it has all the functions of the parent class , These superclasses provide the creation of 、 obtain 、 to update 、 Delete and so on , So we don't need to write additions and deletions, we should check , The view has helped me implement , Example :

At this point the route urls.py

""" resetful URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/v1/users$', views.UserView.as_view({'get':'list','post':'create'})),
    # route ,retrieve、delete、create、update、partial_update, stay UserView The parent class of all implements , among pk Parameters must carry , Want to be key, Class operability 
    url(r'^api/v1/users/(?P<pk>\d+)$', views.UserView.as_view({'get':'retrieve','delete':'destroy','post':'create','put':'update','patch':'partial_update'})),

]
 Copy code 

View views.py

from django.shortcuts import render

# Create your views here.

from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from rest_framework import serializers
from rest_framework import pagination
from rest_framework.viewsets import ModelViewSet
from app01 import models

class Userserializer(serializers.ModelSerializer):   # Serialize class definitions , The previous chapter has described 
    class Meta:
        model = models.UserInfo
        fields = '__all__'  # Serialize fields 

class Mypagination(pagination.PageNumberPagination):  #  Paging class definition , The previous chapters have also introduced 
    """ Custom paging """
    page_size=2  # By default, the number of displays per page is configured 
    page_query_param = 'p' #  Page parameters key, The default is page
    page_size_query_param='size'  #  Specify the number of displays per page parameter 
    max_page_size=4 #  Maximum number of displays per page , Use the above configuration , Can support each page to display 2~4 Data 

class UserView(ModelViewSet):            # View 
    queryset = models.UserInfo.objects.all()  # Data queryset
    serializer_class = Userserializer         #  Serialization classes use 
    permission_classes = []                   #  Permission authentication , There is no certification here , The previous chapter also introduces the authority 
    pagination_class = Mypagination # Paging class , The previous chapters have also introduced 
 Copy code 

visit http://127.0.0.1:8000/api/v1/users/1 , View multiple additions, deletions and modifications .

copyright notice
author[Waiting for],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201312114131656.html

Random recommended