关于drf视图类的封装 Generic((通用视图 普通版本)、(通用视图 特殊版本))、ListModelMixin(5个视图类)、ListAPIView(9个视图类)、ModelViewSet

一 models.py

from django.db import models


# 图书表
class Book(models.Model):
    title = models.CharField(max_length=32, verbose_name='书名')
    price = models.IntegerField(verbose_name='价格')
    publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)
    authors = models.ManyToManyField(to='Author')


# 出版社表
class Publish(models.Model):
    name = models.CharField(max_length=32, verbose_name='出版社名称')
    addr = models.CharField(max_length=32, verbose_name='出版社地址')


# 作者表
class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name='作者姓名')
    age = models.IntegerField(verbose_name='年龄')
    author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE)


# 作者详情表
class AuthorDetail(models.Model):
    gender_choice = ((True, '男'), (False, '女'))
    gender = models.BooleanField(choices=gender_choice, default=True, verbose_name='性别')
    phone = models.CharField(max_length=12, verbose_name='电话')
    addr = models.CharField(max_length=32, verbose_name='作者地址')

二 urls.py

from django.urls import path
# from .views import BookView, BookDetailView, PublishView, PublishDetailView, AuthorView, AuthorDetailView
from .views_GenericAPIView_v1 import BookView, BookDetailView, PublishView, PublishDetailView, AuthorView, AuthorDetailView
# from .views_GenericAPIView import BookView, BookDetailView, PublishView, PublishDetailView, AuthorView, AuthorDetailView
# from .views_FiveAPIView import BookView, BookDetailView, PublishView, PublishDetailView, AuthorView, AuthorDetailView
# from .views_NineAPIView import BookView, BookDetailView, PublishView, PublishDetailView, AuthorView, AuthorDetailView
# from .views_ModelViewSet import BookView, PublishView, AuthorView

#  views_GenericAPIView_v1 views_GenericAPIView views_FiveAPIView views_NineAPIView 路由
urlpatterns = [
    # Book
    path('book/', BookView.as_view()),
    path('book/', BookDetailView.as_view()),

    # Publish
    path('publish/', PublishView.as_view()),
    path('publish/', PublishDetailView.as_view()),

    # Author
    path('author/', AuthorView.as_view()),
    path('author/', AuthorDetailView.as_view()),

]

# # views_ModelViewSet 路由
# urlpatterns = [
#     # Book
#     path('book/', BookView.as_view()),
#     path('book/', BookView.as_view()),
#
#     # Publish
#     path('publish/', PublishView.as_view()),
#     path('publish/', PublishView.as_view()),
#
#     # Author
#     path('author/', AuthorView.as_view()),
#     path('author/', AuthorView.as_view()),
#
# ]

三 serializer.py

import re

from rest_framework import serializers
from .models import Book, Publish, Author, AuthorDetail
from rest_framework.exceptions import ValidationError


# Book
class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['id', 'title', 'price', 'publish', 'authors', 'publish_info', 'authors_detail']
        # 通过额外参数实现 字段校验
        extra_kwargs = {
            'title': {'max_length': 8, 'min_length': 1},
            'price': {'max_value': 999, 'min_value': 1},
            'publish': {'write_only': True},
            'authors': {'write_only': True}
        }

    # 序列化字段
    publish_info = serializers.SerializerMethodField(read_only=True)
    authors_detail = serializers.SerializerMethodField(read_only=True)

    # 定制 publish_info 字段
    def get_publish_info(self, instance: Book):
        return {'name': instance.publish.name, 'addr': instance.publish.addr, }

    # 定制 authors_detail 字段
    def get_authors_detail(self, instance: Book):
        res = {}
        for author in instance.authors.all():
            res[author.pk] = {'name': author.name, 'age': author.age,
                              'gender': author.author_detail.get_gender_display(),
                              'phone': author.author_detail.phone, 'addr': author.author_detail.addr}
        return res

    # 局部钩子
    def validate_title(self, value):
        if re.search('[^\w\s]+', value):
            raise ValidationError('图书名不能包含特殊字符')
        return value

    # 全局钩子
    def validate(self, attrs: dict):
        if attrs.get('title').startswith('sb'):
            raise ValidationError('图书名以sb开头')
        return attrs


# Publish
class PublishSerializer(serializers.ModelSerializer):
    class Meta:
        model = Publish
        fields = '__all__'
        # 通过额外参数实现 字段校验
        extra_kwargs = {
            'name': {'max_length': 12, 'min_length': 1},
            'addr': {'max_length': 32, 'min_length': 1},
        }


# Author
class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ['id', 'name', 'age', 'gender', 'phone', 'addr', 'author_detail']
        # 通过额外参数实现 字段校验
        extra_kwargs = {
            'name': {'max_length': 8, 'min_length': 1},
            'age': {'max_value': 120, 'min_value': 1},
        }

    # 反序列化字段
    gender = serializers.BooleanField(write_only=True)
    phone = serializers.CharField(max_length=11, min_length=1, write_only=True)
    addr = serializers.CharField(max_length=32, min_length=1, write_only=True)
    # 序列化字段
    author_detail = serializers.SerializerMethodField(read_only=True)

    def get_author_detail(self, instance: Author):
        return {
            'name': instance.author_detail.get_gender_display(),
            'phone': instance.author_detail.phone,
            'addr': instance.author_detail.addr
        }

    # 添加
    def create(self, validated_data):
        author_detail = AuthorDetail.objects.create(
            **{key: validated_data.pop(key) for key in ['gender', 'phone', 'addr']})
        auther = Author.objects.create(**validated_data, author_detail=author_detail)
        return auther

    # 更新
    def update(self, instance, validated_data):
        for key in validated_data:
            if hasattr(instance, key):
                setattr(instance, key, validated_data[key])
            else:
                setattr(instance.author_detail, key, validated_data[key])
            instance.author_detail.save()
            instance.save()
        return instance

四 views_GenericAPIView_v1.py (通用视图 普通版本)

from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.response import Response
from .models import Book, Publish, Author
from .serializer import BookSerializer, PublishSerializer, AuthorSerializer


##################### GenericAPIView 类 ##########################
class GenericAPIView(APIView):
    model = None
    serializer_cls = None


##################### GenericAPIView 类 ##########################

# Book 视图函数
class BookView(GenericAPIView):
    model = Book
    serializer_cls = BookSerializer

    def get(self, request: Request):
        books = self.model.objects.all()
        ser = self.serializer_cls(instance=books, many=True)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})

    def post(self, request: Request):
        ser = self.serializer_cls(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '新增失败', 'result': ser.errors})


class BookDetailView(GenericAPIView):
    model = Book
    serializer_cls = BookSerializer

    def get(self, request: Request, pk):
        book = self.model.objects.filter(pk=pk).first()
        if not book:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=book, many=False)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})

    def put(self, request: Request, pk):
        book = self.model.objects.filter(pk=pk).first()
        if not book:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '修改成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '修改失败', 'result': ser.errors})

    def delete(self, request: Request, pk):
        book = self.model.objects.filter(pk=pk).first()
        if not book:
            return Response({'code': 101, 'msg': 'pk不存在'})
        book.delete()
        return Response({'code': 100, 'msg': '删除成功', 'result': {}})


# Publish 视图函数
class PublishView(GenericAPIView):
    model = Publish
    serializer_cls = PublishSerializer

    def get(self, request: Request):
        publishs = self.model.objects.all()
        ser = self.serializer_cls(instance=publishs, many=True)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})

    def post(self, request: Request):
        ser = self.serializer_cls(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '新增失败', 'result': ser.errors})


class PublishDetailView(GenericAPIView):
    model = Publish
    serializer_cls = PublishSerializer

    def get(self, request: Request, pk):
        publish = self.model.objects.filter(pk=pk).first()
        if not publish:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=publish, many=False)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})

    def put(self, request: Request, pk):
        publish = self.model.objects.filter(pk=pk).first()
        if not publish:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=publish, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '修改成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '修改失败', 'result': ser.errors})

    def delete(self, request: Request, pk):
        publish = self.model.objects.filter(pk=pk).first()
        if not publish:
            return Response({'code': 101, 'msg': 'pk不存在'})
        publish.delete()
        return Response({'code': 100, 'msg': '删除成功', 'result': {}})


# Author 视图函数
class AuthorView(GenericAPIView):
    model = Author
    serializer_cls = AuthorSerializer

    def get(self, request: Request):
        authors = self.model.objects.all()
        ser = self.serializer_cls(instance=authors, many=True)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})

    def post(self, request: Request):
        ser = self.serializer_cls(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '新增失败', 'result': ser.errors})


class AuthorDetailView(GenericAPIView):
    model = Author
    serializer_cls = AuthorSerializer

    def get(self, request: Request, pk):
        author = self.model.objects.filter(pk=pk).first()
        if not author:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=author, many=False)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})

    def put(self, request: Request, pk):
        author = self.model.objects.filter(pk=pk).first()
        if not author:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=author, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '修改成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '修改失败', 'result': ser.errors})

    def delete(self, request: Request, pk):
        author = self.model.objects.filter(pk=pk).first()
        if not author:
            return Response({'code': 101, 'msg': 'pk不存在'})
        author.delete()
        return Response({'code': 100, 'msg': '删除成功', 'result': {}})

五 views_GenericAPIView.py (通用视图 特殊版本)

from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.response import Response
from .models import Book, Publish, Author
from .serializer import BookSerializer, PublishSerializer, AuthorSerializer


##################### GenericAPIView 类 ##########################
class GenericAPIView(APIView):
    model = None
    serializer_cls = None

    def __init__(self, *args, **kwargs):
        # 获取视图类名
        full_class_name = self.__class__.__name__
        # 获取模型类
        class_name = ''
        flag = False
        for s in full_class_name:
            if s.isupper() and flag:
                break
            if s.isupper():
                flag = True
            class_name += s
        self.model = globals()[class_name]
        # 获取序列化类
        serializer_class_name = class_name + 'Serializer'
        self.serializer_cls = globals()[serializer_class_name]

        super().__init__(*args, **kwargs)


##################### GenericAPIView 类 ##########################

# Book 视图函数
class BookView(GenericAPIView):
    def get(self, request: Request):
        books = self.model.objects.all()
        ser = self.serializer_cls(instance=books, many=True)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})

    def post(self, request: Request):
        ser = self.serializer_cls(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '新增失败', 'result': ser.errors})


class BookDetailView(GenericAPIView):
    def get(self, request: Request, pk):
        book = self.model.objects.filter(pk=pk).first()
        if not book:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=book, many=False)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})

    def put(self, request: Request, pk):
        book = self.model.objects.filter(pk=pk).first()
        if not book:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '修改成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '修改失败', 'result': ser.errors})

    def delete(self, request: Request, pk):
        book = self.model.objects.filter(pk=pk).first()
        if not book:
            return Response({'code': 101, 'msg': 'pk不存在'})
        book.delete()
        return Response({'code': 100, 'msg': '删除成功', 'result': {}})


# Publish 视图函数
class PublishView(GenericAPIView):
    def get(self, request: Request):
        publishs = self.model.objects.all()
        ser = self.serializer_cls(instance=publishs, many=True)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})

    def post(self, request: Request):
        ser = self.serializer_cls(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '新增失败', 'result': ser.errors})


class PublishDetailView(GenericAPIView):
    def get(self, request: Request, pk):
        publish = self.model.objects.filter(pk=pk).first()
        if not publish:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=publish, many=False)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})

    def put(self, request: Request, pk):
        publish = self.model.objects.filter(pk=pk).first()
        if not publish:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=publish, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '修改成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '修改失败', 'result': ser.errors})

    def delete(self, request: Request, pk):
        publish = self.model.objects.filter(pk=pk).first()
        if not publish:
            return Response({'code': 101, 'msg': 'pk不存在'})
        publish.delete()
        return Response({'code': 100, 'msg': '删除成功', 'result': {}})


# Author 视图函数
class AuthorView(GenericAPIView):
    def get(self, request: Request):
        authors = self.model.objects.all()
        ser = self.serializer_cls(instance=authors, many=True)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})

    def post(self, request: Request):
        ser = self.serializer_cls(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '新增失败', 'result': ser.errors})


class AuthorDetailView(GenericAPIView):
    def get(self, request: Request, pk):
        author = self.model.objects.filter(pk=pk).first()
        if not author:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=author, many=False)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})

    def put(self, request: Request, pk):
        author = self.model.objects.filter(pk=pk).first()
        if not author:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=author, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '修改成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '修改失败', 'result': ser.errors})

    def delete(self, request: Request, pk):
        author = self.model.objects.filter(pk=pk).first()
        if not author:
            return Response({'code': 101, 'msg': 'pk不存在'})
        author.delete()
        return Response({'code': 100, 'msg': '删除成功', 'result': {}})

六 views_FiveAPIView.py (5个视图类)

from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.response import Response
from .models import Book, Publish, Author
from .serializer import BookSerializer, PublishSerializer, AuthorSerializer


# GenericAPIView 类
class GenericAPIView(APIView):
    model = None
    serializer_cls = None

    def __init__(self, *args, **kwargs):
        # 获取视图类名
        full_class_name = self.__class__.__name__
        # 获取模型类
        class_name = ''
        flag = False
        for s in full_class_name:
            if s.isupper() and flag:
                break
            if s.isupper():
                flag = True
            class_name += s
        self.model = globals()[class_name]
        # 获取序列化类
        serializer_class_name = class_name + 'Serializer'
        self.serializer_cls = globals()[serializer_class_name]

        super().__init__(*args, **kwargs)


####################### 5个Mixin类 ###########################
# CreateModelMixin 类
class CreateModelMixin:
    def create(self, request, *args, **kwargs):
        ser = self.serializer_cls(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '新增失败', 'result': ser.errors})


# ListModelMixin 类
class ListModelMixin:
    def list(self, request, *args, **kwargs):
        books = self.model.objects.all()
        ser = self.serializer_cls(instance=books, many=True)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})


# RetrieveModelMixin 类
class RetrieveModelMixin:
    def retrieve(self, request, pk, *args, **kwargs):
        book = self.model.objects.filter(pk=pk).first()
        if not book:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=book, many=False)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})


# UpdateModelMixin 类
class UpdateModelMixin:
    def update(self, request, pk, *args, **kwargs):
        book = self.model.objects.filter(pk=pk).first()
        if not book:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '修改成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '修改失败', 'result': ser.errors})


# DestroyModelMixin 类
class DestroyModelMixin:
    def destroy(self, request, pk, *args, **kwargs):
        book = self.model.objects.filter(pk=pk).first()
        if not book:
            return Response({'code': 101, 'msg': 'pk不存在'})
        book.delete()
        return Response({'code': 100, 'msg': '删除成功', 'result': {}})


####################### 5个Mixin类 ###########################

# Book 视图函数
class BookView(GenericAPIView, ListModelMixin, CreateModelMixin):
    def get(self, request: Request):
        return self.list(request)

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


class BookDetailView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
    def get(self, request: Request, pk):
        return self.retrieve(request, pk)

    def put(self, request: Request, pk):
        return self.update(request, pk)

    def delete(self, request: Request, pk):
        return self.destroy(request, pk)


# Publish 视图函数
class PublishView(GenericAPIView, ListModelMixin, CreateModelMixin):
    def get(self, request: Request):
        return self.list(request)

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


class PublishDetailView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
    def get(self, request: Request, pk):
        return self.retrieve(request, pk)

    def put(self, request: Request, pk):
        return self.update(request, pk)

    def delete(self, request: Request, pk):
        return self.destroy(request, pk)


# Author 视图函数
class AuthorView(GenericAPIView, ListModelMixin, CreateModelMixin):
    def get(self, request: Request):
        return self.list(request)

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


class AuthorDetailView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
    def get(self, request: Request, pk):
        return self.retrieve(request, pk)

    def put(self, request: Request, pk):
        return self.update(request, pk)

    def delete(self, request: Request, pk):
        return self.destroy(request, pk)

七 views_NineAPIView.py (9个视图类)

from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.response import Response
from .models import Book, Publish, Author
from .serializer import BookSerializer, PublishSerializer, AuthorSerializer


# GenericAPIView 类
class GenericAPIView(APIView):
    model = None
    serializer_cls = None

    def __init__(self, *args, **kwargs):
        # 获取视图类名
        full_class_name = self.__class__.__name__
        # 获取模型类
        class_name = ''
        flag = False
        for s in full_class_name:
            if s.isupper() and flag:
                break
            if s.isupper():
                flag = True
            class_name += s
        self.model = globals()[class_name]
        # 获取序列化类
        serializer_class_name = class_name + 'Serializer'
        self.serializer_cls = globals()[serializer_class_name]

        super().__init__(*args, **kwargs)


# CreateModelMixin 类
class CreateModelMixin:
    def create(self, request, *args, **kwargs):
        ser = self.serializer_cls(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '新增失败', 'result': ser.errors})


# ListModelMixin 类
class ListModelMixin:
    def list(self, request, *args, **kwargs):
        books = self.model.objects.all()
        ser = self.serializer_cls(instance=books, many=True)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})


# RetrieveModelMixin 类
class RetrieveModelMixin:
    def retrieve(self, request, pk, *args, **kwargs):
        book = self.model.objects.filter(pk=pk).first()
        if not book:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=book, many=False)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})


# UpdateModelMixin 类
class UpdateModelMixin:
    def update(self, request, pk, *args, **kwargs):
        book = self.model.objects.filter(pk=pk).first()
        if not book:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '修改成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '修改失败', 'result': ser.errors})


# DestroyModelMixin 类
class DestroyModelMixin:
    def destroy(self, request, pk, *args, **kwargs):
        book = self.model.objects.filter(pk=pk).first()
        if not book:
            return Response({'code': 101, 'msg': 'pk不存在'})
        book.delete()
        return Response({'code': 100, 'msg': '删除成功', 'result': {}})


################## 9个APIView类 ####################

class CreateAPIView(GenericAPIView, CreateModelMixin):
    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)


class ListAPIView(GenericAPIView, ListModelMixin):
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)


class RetrieveAPIView(GenericAPIView, RetrieveModelMixin):
    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)


class DestroyAPIView(GenericAPIView, DestroyModelMixin):
    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)


class UpdateAPIView(GenericAPIView, UpdateModelMixin):
    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)


class ListCreateAPIView(GenericAPIView, ListModelMixin, CreateModelMixin):
    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 RetrieveUpdateAPIView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin):
    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

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


class RetrieveDestroyAPIView(GenericAPIView, RetrieveModelMixin, DestroyModelMixin):
    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

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


class RetrieveUpdateDestroyAPIView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
    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)


################## 9个APIView类 ####################


# Book 视图函数
class BookView(ListCreateAPIView):
    pass


class BookDetailView(RetrieveUpdateDestroyAPIView):
    pass


# Publish 视图函数
class PublishView(ListCreateAPIView):
    pass


class PublishDetailView(RetrieveUpdateDestroyAPIView):
    pass


# Author 视图函数
class AuthorView(ListCreateAPIView):
    pass


class AuthorDetailView(RetrieveUpdateDestroyAPIView):
    pass

八 views_ModelViewSet.py (ModelViewSet视图类)

from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.response import Response
from .models import Book, Publish, Author
from .serializer import BookSerializer, PublishSerializer, AuthorSerializer
from django.views.decorators.csrf import csrf_exempt


# GenericAPIView 类
class GenericAPIView(APIView):
    model = None
    serializer_cls = None

    def __init__(self, *args, **kwargs):
        # 获取视图类名
        full_class_name = self.__class__.__name__
        # 获取模型类
        class_name = ''
        flag = False
        for s in full_class_name:
            if s.isupper() and flag:
                break
            if s.isupper():
                flag = True
            class_name += s
        self.model = globals()[class_name]
        # 获取序列化类
        serializer_class_name = class_name + 'Serializer'
        self.serializer_cls = globals()[serializer_class_name]

        super().__init__(*args, **kwargs)


# CreateModelMixin 类
class CreateModelMixin:
    def create(self, request, *args, **kwargs):
        ser = self.serializer_cls(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '新增失败', 'result': ser.errors})


# ListModelMixin 类
class ListModelMixin:
    def list(self, request, *args, **kwargs):
        books = self.model.objects.all()
        ser = self.serializer_cls(instance=books, many=True)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})


# RetrieveModelMixin 类
class RetrieveModelMixin:
    def retrieve(self, request, pk, *args, **kwargs):
        book = self.model.objects.filter(pk=pk).first()
        if not book:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=book, many=False)
        return Response({'code': 100, 'msg': '查询成功', 'result': ser.data})


# UpdateModelMixin 类
class UpdateModelMixin:
    def update(self, request, pk, *args, **kwargs):
        book = self.model.objects.filter(pk=pk).first()
        if not book:
            return Response({'code': 101, 'msg': 'pk不存在'})
        ser = self.serializer_cls(instance=book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '修改成功', 'result': ser.data})
        return Response({'code': 101, 'msg': '修改失败', 'result': ser.errors})


# DestroyModelMixin 类
class DestroyModelMixin:
    def destroy(self, request, pk, *args, **kwargs):
        book = self.model.objects.filter(pk=pk).first()
        if not book:
            return Response({'code': 101, 'msg': 'pk不存在'})
        book.delete()
        return Response({'code': 100, 'msg': '删除成功', 'result': {}})


################## ModelViewSet类 ####################
class ModelViewSet(GenericAPIView, CreateModelMixin, ListModelMixin, RetrieveModelMixin, UpdateModelMixin,
                   DestroyModelMixin):
    @classmethod
    def as_view(cls, **initkwargs):
        def view(request, *args, **kwargs):
            actions = {'get': 'list', 'post': 'create'}
            if kwargs.get('pk'):
                actions = {'get': 'retrieve', 'put': 'update', 'delete': 'destroy'}
            self = cls(**initkwargs)
            for method, action in actions.items():
                handler = getattr(self, action)
                setattr(self, method, handler)
            return self.dispatch(request, *args, **kwargs)

        return csrf_exempt(view)


################## ModelViewSet类 ####################

# Book 视图函数
class BookView(ModelViewSet):
    pass


# Publish 视图函数
class PublishView(ModelViewSet):
    pass


# Author 视图函数
class AuthorView(ModelViewSet):
    pass

你可能感兴趣的:(django,python01,sqlite,django,python,windows,pycharm)