DRF Django REST framework assembly view of (d)

introduction

In our view there are tens of hundreds of classes, there are get, post and other methods, when a similar function, can cause a lot of code duplication occurs, obviously there are many places that can be optimized. This will have a view of the assembly, it's very powerful, well optimized interface logic.

Component view

Using a view interface logic optimization component mixin

  1. Import  mixins 
  2. Defined sequence classes
  3. View class definitions
# 1. Import as mixins
 from rest_framework.mixins Import ( 
    ListModelMixin, 
    CreateModelMixin, 
    DestroyModelMixin, 
    UpdateModelMixin, 
    RetrieveModelMixin 
) 
from rest_framework.generics Import GenericAPIView 

from DrfOne Import Models
 # 2. sequence defined classes
 from DrfOne.drf_serializers Import BookSerializer 


# 3. view class definitions
 class BookView (ListModelMixin, CreateModelMixin, GenericAPIView):
     # acquire a data source, the fixed wording 
    queryset =models.Book.objects.all ()
     # sequence of categories, the fixed wording 
    serializer_class = BookSerializer
     DEF GET (Self, Request, * args, ** kwargs):
         return self.list (Request, * args, ** kwargs) 

    DEF POST (Self, Request, * args, ** kwargs):
         return self.create (Request, * args, ** kwargs) 


class BookFilterView (RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin, GenericAPIView):
     # acquire a data source, the fixed wording 
    QuerySet = Models. Book.objects.all ()
     # sequence of categories, the fixed wording 
    serializer_class = BookSerializer 

    DEF get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

Defined sequence classes

from rest_framework import serializers

from DrfOne import models


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Book
        fields = "__all__"
        extra_kwargs = {
            # 仅写
            "publish": {'write_only': True},
            "authors": {'write_only': True},
        }

    publish_name = serializers.CharField(max_length=32, read_only=True, source="publish.name")
    publish_address = serializers.CharField(max_length=32, read_only=True, source="publish.address")
    author_name = serializers.SerializerMethodField()

    def get_author_name(self, book_obj):
        author_list = list()
        for author in book_obj.authors.all():
            # 注意列表添加字段,author.name而不是author
            author_list.append(author.name)
        return author_list

Note: Operation of the single piece of data  url 

from django.urls import path, re_path

from DrfOne import views

urlpatterns = [
    path('books/', views.BookView.as_view()),
    # 需要命名为pk
    re_path("books/(?P<pk>\d+)/", views.BookFilterView.as_view()),
]

The above code is found by  GET  ,  POST  , etc. The method is similar to the content, it can be resealed.

Optimization of view using a view interface logic components

  1. Import  generics 
  2. Sequence introduced class
  3. View class definitions

Of  mixins  to optimize the rest unchanged again

# 1. Import generics 
from rest_framework Import generics 

from DrfOne Import Models
 # 2. introduced sequence class 
from DrfOne.drf_serializers Import BookSerializer 


# 3. view class defines 
class BookView (generics.ListCreateAPIView):
     # acquire a data source, the fixed wording 
    QuerySet = Models .Book.objects.all ()
     # sequence of categories, the fixed wording 
    serializer_class = BookSerializer 


class BookFilterView (generics.RetrieveUpdateDestroyAPIView): 
    QuerySet = models.Book.objects.all () 
    serializer_class = BookSerializer

I found that there are duplicate code, optimized once again, that is  Viewset  .

Using a view interface logic optimization component viewset

It appears to have optimized perfect, but at a very high performance requirements of the project which, we can continue to optimize the program, continuous optimization program is an essential skill for every programmer.

  1. Defined  url 
  2. Import  viewset 
  3. Sequence introduced class
  4. View class definitions

Note the change urls.py

from django.urls import path, re_path

from DrfOne import views


urlpatterns = [
    # path('books/', views.BookView.as_view()),
    # re_path("books/(?P<pk>\d+)/", views.BookFilterView.as_view()),

    path("books/", views.BookView.as_view({
        "get": "list",
        "post": "create",
    })),
    re_path('books/(?P<pk>\d+)/', views.BookView.as_view({
        'get': 'retrieve',
        'put': 'update',
        'delete': 'destroy'
    })),
]

views.py

# 2 in the import module viewset ModelViewSet class 
from rest_framework.viewsets Import ModelViewSet 

# Import application in the Models 
from DrfOne Import Models
 # 3. introduced sequence class 
from DrfOne.drf_serializers Import BookSerializer 

# 4. view class defines 
class BookView (ModelViewSet) :
     # acquire a data source, the fixed wording 
    QuerySet = models.Book.objects.all ()
     # sequence of categories, the fixed wording 
    serializer_class = BookSerializer

~>.<~

Guess you like

Origin www.cnblogs.com/pungchur/p/12028325.html