drf-5个接口

写接口前的准备

1 表模型

from django.db import models


class Book(models.Model):
    name = models.CharField(max_length=32)
    price = models.CharField(max_length=32)

    publish = models.ForeignKey(to='Publish', on_delete=models.DO_NOTHING, null=True, db_constraint=False)
    authors = models.ManyToManyField(to='Author')


class Publish(models.Model):
    name = models.CharField(max_length=32)
    addr = models.CharField(max_length=32)


class Author(models.Model):
    name = models.CharField(max_length=32)
    phone = models.CharField(max_length=11)
    # 本质就是ForeignKey,但是唯一,多的一方唯一,形成了一对一
    author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE)


class AuthorDetail(models.Model):
    email = models.CharField(max_length=32)
    age = models.IntegerField()

序列化类

from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'

一 继承APIView+序列化类+Resonse写5个接口

视图类

from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Book
from .serializer import BookSerializer


class BookView(APIView):
    def get(self, request):
        book_list = Book.objects.all()
        ser = BookSerializer(book_list, many=True)
        return Response({'code': 100, 'msg': '查询所有成功', 'data': ser.data})

    def post(self, request):
        ser = BookSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增成功'})
        else:
            return Response({'code': 100, 'msg': ser.errors})


class BookDetailView(APIView):
    def get(self, request, pk):
        book = Book.objects.filter(pk=pk).first()
        ser = BookSerializer(book)
        return Response({'code': 101, 'msg': '查询一条成功', 'data': ser.data})

    def put(self, request, pk):
        book = Book.objects.filter(pk=pk).filter()
        ser = BookSerializer(book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '更新成功'})
        else:
            return Response({'code': 101, 'msg': ser.errors})

    def delete(self, request, pk):
        Book.objects.fiter(pk=pk).delete()
        return Response({'code': 100, 'msg': '删除成功'})

路由

urlpatterns = [
    path('books/', views.BookView.as_view()),
    path('books/<int:pk>/', views.BookDetailView.as_view()),
]

二 继承GenericAPIView + 序列化类 + Resonse写5个接口

视图类

from .models import Book
from .serializer import BookSerializer
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView


class BookView(GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def get(self, request):
        book_list = self.get_queryset()
        ser = self.get_serializer(book_list, many=True)
        return Response({'code': 100, 'msg': '成功', 'results': ser.data})

    def post(self, request):
        ser = self.get_serializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '成功'})
        else:
            return Response({'code': 101, 'msg': ser.errors})


class BookDetailView(GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def get(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(book)
        return Response({'code': 100, 'msg': '成功', 'results': ser.data})

    def post(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '更新成功'})
        else:
            return Response({'code': 101, 'msg': ser.errors})

    def delete(self, request, pk):
        self.get_object().delete()
        return Response({'code': 100, 'msg': '删除成功'})

路由

urlpatterns = [
    path('books/', views.BookView.as_view()),
    path('books/<int:pk>/', views.BookDetailView.as_view()),
]

三 继承GenericAPIView+5个视图扩展类+序列化类+Response写接口

视图类

from .models import Book
from .serializer import BookSerializer
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, \
    DestroyModelMixin


class BookView(GenericAPIView, ListModelMixin, CreateModelMixin):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def get(self, request):
        return self.list(request)

    def post(self, request):
        return self.create(request)


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

路由

urlpatterns = [
    path('books/', views.BookView.as_view()),
    path('books/<int:pk>/', views.BookDetailView.as_view()),
]

四 基于视图子类写5 个接口:9个视图子类--->视图类

单独使用5个类:

视图类

from .models import Book
from .serializer import BookSerializer
from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView, DestroyAPIView


class BookView(ListAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer


class BookView(CreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer


class BookDetailView(RetrieveAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer


class BookDetailView(UpdateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer


class BookDetailView(DestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

路由

urlpatterns = [
    path('books/', views.BookView.as_view()),
    path('books/<int:pk>/', views.BookDetailView.as_view()),
]

使用复合的类:

视图类

from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView, RetrieveDestroyAPIView, \
    RetrieveUpdateAPIView


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


class BookDetailView(RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

路由

urlpatterns = [
    path('books/', views.BookView.as_view()),
    path('books/<int:pk>/', views.BookDetailView.as_view()),
]

上面的所有方法中使用的路由都一致,都是原始写法。

五 视图集合

5.1 ModelViewSet

视图类

from .models import Book
from .serializer import BookSerializer
from rest_framework.viewsets import ModelViewSet


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

路由

urlpatterns = [
    path('books/', views.BookView.as_view({'get': 'list', 'post': 'create'})),
    path('books/<int:pk>/', views.BookView.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
]

# 也可以使用自动生成路由

5.2 ReadOnlyModelViewSet,只有两个方法

视图类

from .models import Book
from .serializer import BookSerializer
from rest_framework.viewsets import ReadOnlyModelViewSet


class BookView(ReadOnlyModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

路由

urlpatterns = [
    path('books/', views.BookView.as_view({'get': 'list'})),
    path('books/<int:pk>/', views.BookView.as_view({'get': 'retrieve'})),
]

# 也可以使用自动生成路由

5.3 ViewSetMixin

视图类

from .models import Book
from .serializer import BookSerializer
from rest_framework.viewsets import ViewSetMixin
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView


class BookView(ViewSetMixin, ListCreateAPIView, RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

路由

路由可以这么写:

urlpatterns = [
    path('books/', views.BookView.as_view({'get': 'list', 'post': 'create'})),
    path('books/<int:pk>/', views.BookView.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
]

# 也可以使用自动生成路由

5.4 ViewSet

ViewSet =ViewSetMixin+APIView

视图类

from .models import Book
from .serializer import BookSerializer
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet


class BookView(ViewSet):
    def list(self, request):
        book_list = Book.objects.all()
        ser = BookSerializer(book_list, many=True)
        return Response({'code': 100, 'msg': '查询所有成功', 'data': ser.data})

    def create(self, request):
        ser = BookSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增成功'})
        else:
            return Response({'code': 100, 'msg': ser.errors})

    def retrieve(self, request, pk):
        book = Book.objects.filter(pk=pk).first()
        ser = BookSerializer(book)
        return Response({'code': 101, 'msg': '查询一条成功', 'data': ser.data})

    def update(self, request, pk):
        book = Book.objects.filter(pk=pk).filter()
        ser = BookSerializer(book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '更新成功'})
        else:
            return Response({'code': 101, 'msg': ser.errors})

    def destroy(self, request, pk):
        Book.objects.fiter(pk=pk).delete()
        return Response({'code': 100, 'msg': '删除成功'})

路由

urlpatterns = [
    path('books/', views.BookView.as_view({'get': 'list', 'post': 'create'})),
    path('books/<int:pk>/', views.BookView.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
]

# 也可以使用自动生成路由

5.5 GenericViewSet

GenericViewSet = ViewSetMixin+GenericAPIView

视图类

from .models import Book
from .serializer import BookSerializer
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet


class BookView(GenericViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def list(self, request):
        book_list = self.get_queryset()
        ser = self.get_serializer(book_list, many=True)
        return Response({'code': 100, 'msg': '成功', 'results': ser.data})

    def create(self, request):
        ser = self.get_serializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '成功'})
        else:
            return Response({'code': 101, 'msg': ser.errors})

    # class BookDetailView(GenericAPIView):
    #     queryset = Book.objects.all()
    #     serializer_class = BookSerializer

    def retrieve(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(book)
        return Response({'code': 100, 'msg': '成功', 'results': ser.data})

    def update(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '更新成功'})
        else:
            return Response({'code': 101, 'msg': ser.errors})

    def destroy(self, request, pk):
        self.get_object().delete()
        return Response({'code': 100, 'msg': '删除成功'})

路由

urlpatterns = [
    path('books/', views.BookView.as_view({'get': 'list', 'post': 'create'})),
    path('books/<int:pk>/', views.BookView.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
]

# 也可以使用自动生成路由

posted @ 2023-05-25 21:01  星空看海  阅读(35)  评论(0编辑  收藏  举报