1. 程式人生 > >django的檢視元件

django的檢視元件

對之前使用檢視元件進行介面優化

  1.使用檢視元件的mixin進行介面邏輯優

  匯入mixin

from rest_framework.mixinx import (
    ListModelMix,
    CreateModelMixin,
    DestroyModelMixin,
    UpdateModelMixin,
    RetrieveModelMixin
)

  models.py

from django.db import models

# Create your models here.

class Author(models.Model):
    nid 
= models.AutoField(primary_key=True) name = models.CharField(max_length=32) age = models.IntegerField() def __str__(self): return self.name class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email
= models.EmailField() def __str__(self): return self.name class Book(models.Model): nid = models.AutoField(primary_key=True) title = models.CharField(max_length=32) price = models.DecimalField(max_digits=5,decimal_places=2) publish = models.ForeignKey(to="Publish",related_name="
book",related_query_name="book_query",on_delete=models.CASCADE) authors = models.ManyToManyField(to="Author")

  urls.py

from django.contrib import admin
from django.urls import path,re_path
from app01 import views

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

]    

  view.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.mixins import (
    ListModelMixin, CreateModelMixin, DestroyModelMixin, UpdateModelMixin, RetrieveModelMixin
)

from app01.models import (
    Book,Publish,Author
)
from .app_serializers import BookSerializer


class BookView(ListModelMixin, CreateModelMixin, GenericAPIView):
    queryset = Book.objects.all()
    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, DestroyModelMixin, UpdateModelMixin, GenericAPIView):
    queryset = Book.objects.all()
    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)

  注意:單條資料操作的url是這樣的:re_path(r'books/(?P<pk>\d+)/$, views.BookFilterView.as_view())

還可以進行優化---使用檢視元件的view進行介面邏輯優化

  匯入模組

from rest_framework import generics

  可以把改 view.py

class BookView(generics.ListCreateAPIView)
     queryset = Book.objects.all()
     serializer_class = BookSerializer
                    
class BookFilterView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer    

最後改成------使用檢視元件的viewset進行介面邏輯優化

  匯入模組

from rest_framework.viewsets import ModelViewSet

  urls.py

from django.contrib import admin
from django.urls import path,re_path
from app01 import views

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

  view.py

class BookView(ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer1