标签:import 分页 extension elm text perm div retrieve arch
1.常用配置
import django_filters from django.db.models import Q from rest_framework.pagination import PageNumberPagination from rest_framework_extensions.cache.mixins import CacheResponseMixin from rest_framework import mixins from rest_framework import viewsets from django_filters.rest_framework import DjangoFilterBackend from rest_framework import filters from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework import permissions from .models import Goods class GoodsFilter(django_filters.rest_framework.FilterSet): """ 商品的过滤类 """ pricemin = django_filters.NumberFilter(field_name=‘shop_price‘, help_text="最低价格", lookup_expr=‘gte‘) pricemax = django_filters.NumberFilter(field_name=‘shop_price‘, lookup_expr=‘lte‘) top_category = django_filters.NumberFilter(method=‘top_category_filter‘) def top_category_filter(self, queryset, name, value): return queryset.filter(Q(category_id=value) | Q(category__parent_category_id=value) | Q( category__parent_category__parent_category_id=value)) class Meta: model = Goods fields = [‘pricemin‘, ‘pricemax‘, ‘is_hot‘, ‘is_new‘] class GoodsPagination(PageNumberPagination): ‘‘‘ 分页设置 ‘‘‘ page_size = 10 page_size_query_param = ‘page_size‘ page_query_param = "page" max_page_size = 100 class IsOwnerOrReadOnly(permissions.BasePermission): """ 权限配置 """ # 先执行 has_permission 任何执行has_object_permission 函数 def has_permission(self, request, view): pass def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we‘ll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: return True # Instance must have an attribute named `owner`. return obj.user == request.user # 缓存 setting配置 REST_FRAMEWORK_EXTENSIONS = { # 缓存时间 ‘DEFAULT_CACHE_RESPONSE_TIMEOUT‘: 60 * 60, # 缓存存储 ‘DEFAULT_USE_CACHE‘: ‘default‘, } # CacheResponseMixin 缓存 class GoodsListViewSet(CacheResponseMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """ 商品列表页, 分页, 搜索, 过滤, 排序 """ # throttle_classes = (UserRateThrottle, ) queryset = Goods.objects.all() serializer_class = GoodsSerializer # 分页配置 pagination_class = GoodsPagination # 登入认证 authentication_classes = (JSONWebTokenAuthentication,) # 过滤配置 DjangoFilterBackend 搜索配置SearchFilter 排序配置OrderingFilter filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter) # 过滤 filter_class = GoodsFilter # 搜索 search_fields = (‘name‘, ‘goods_brief‘, ‘goods_desc‘) # 排序 ordering_fields = (‘sold_num‘, ‘shop_price‘) # 权限认证 IsAuthenticated允许任何认证用户访问 IsAuthenticatedOrReadOnly为验证身份用户可以读 permission_classes = (permissions.IsAuthenticated, IsOwnerOrReadOnly)
aa
标签:import 分页 extension elm text perm div retrieve arch
原文地址:https://www.cnblogs.com/yoyo1216/p/10614327.html