一 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_GenericAPIView_v1 import BookView, BookDetailView, PublishView, PublishDetailView, AuthorView, AuthorDetailView
urlpatterns = [
path('book/', BookView.as_view()),
path('book/', BookDetailView.as_view()),
path('publish/', PublishView.as_view()),
path('publish/', PublishDetailView.as_view()),
path('author/', AuthorView.as_view()),
path('author/', AuthorDetailView.as_view()),
]
三 serializer.py
import re
from rest_framework import serializers
from .models import Book, Publish, Author, AuthorDetail
from rest_framework.exceptions import ValidationError
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)
def get_publish_info(self, instance: Book):
return {'name': instance.publish.name, 'addr': instance.publish.addr, }
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
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},
}
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
class GenericAPIView(APIView):
model = None
serializer_cls = None
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': {}})
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': {}})
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
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)
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': {}})
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': {}})
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
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)
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})
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})
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})
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})
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': {}})
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)
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)
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
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)
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})
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})
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})
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})
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': {}})
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)
class BookView(ListCreateAPIView):
pass
class BookDetailView(RetrieveUpdateDestroyAPIView):
pass
class PublishView(ListCreateAPIView):
pass
class PublishDetailView(RetrieveUpdateDestroyAPIView):
pass
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
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)
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})
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})
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})
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})
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': {}})
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)
class BookView(ModelViewSet):
pass
class PublishView(ModelViewSet):
pass
class AuthorView(ModelViewSet):
pass