1.GenericAPIView 和mixins 的使用:
1.1 在 user/urls.py 中添加路由
from django.contrib import admin
from django.urls import path
from dayapp.views import *
urlpatterns = [
path('admin/', admin.site.urls),
path('cate', CateView.as_view()),
path('cate/<int:pk>/', CateInfoView.as_view()),#修改和删除重新写一个视图
path('good', GoodView.as_view()),
path('good/<int:pk>/', GoodInfoView.as_view()),#修改和删除重新写一个视图
]
1.2创建user/serializers.py写序列化器
from rest_framework import serializers
from .models import *
from rest_framework.validators import ValidationError
class Cateser(serializers.ModelSerializer):
class Meta:
model = Cate
fields = '__all__'
class Goodser(serializers.ModelSerializer):
# 自定义验证上传图片
pic = serializers.ImageField(use_url=False)
def validate_pic(self, file):
# 获取文件名 大小
name = file.name
size = file.size # 大小返回的单位是字节数
print(name, size) # 打印文件名 文件大小
if size > 2 * 1024 * 1024:
raise ValidationError('文件大小超过2M') # 抛出异常
else:
pass
if name.split(".")[-1] not in ("jpg", "jpeg"):
raise ValidationError('文件格式不是jpg或jpeg') # 抛出异常
return file
class Meta:
model = Good
fields = '__all__'
1.3 在 user/views.py 中添加视图函数
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin,CreateModelMixin,
RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin
from .sers import *
# 导入列表分页类
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class CateView(GenericAPIView, ListModelMixin, CreateModelMixin):
queryset = Cate.objects.all()
serializer_class = Cateser
def get(self, request): #查询
return self.list(request)
def post(self, request): #增加
response = self.create(request)
return response
class CateInfoView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
queryset = Cate.objects.all()
serializer_class = Cateser
def get(self, request, pk): # 检索
return self.retrieve(request)
def put(self, request, pk): #修改
return self.partial_update(request) # partial_update 部分更新
def delete(self, request, pk): #删除
return self.destroy(request)
#自定义分页
class BookPage(PageNumberPagination):
page_size = 3 # 设置 一页 大小
page_query_param = 'p' # 重新配置页码的参数名
def get_paginated_response(self, data): # data 是本页的数据
# 我们需要返回 上一页页码 下一页页码 当前页的数据 还有总页数
number = self.page.number # 当前页数
page_nums = self.page.paginator.num_pages # 总页数
if number > 1:
prev_number = number - 1
else:
prev_number = None
if number < page_nums:
next_number = number + 1
else:
next_number = None
resp = {}
resp['prev_number'] = prev_number
resp['next_number'] = next_number
resp['page_nums'] = page_nums
resp['data'] = data
return Response(resp)
class GoodView(GenericAPIView, ListModelMixin, CreateModelMixin):
queryset = Good.objects.all()
serializer_class = Goodser
# 设置列表分页
pagination_class = BookPage
def get(self, request):
return self.list(request)
def post(self, request):
response = self.create(request)
return response
class GoodInfoView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
queryset = Good.objects.all()
serializer_class = Goodser
def get(self, request, pk): # 检索
return self.retrieve(request)
def put(self, request, pk):
return self.partial_update(request)
def delete(self, request, pk):
return self.destroy(request)