码迷,mamicode.com
首页 > 其他好文 > 详细

django def django-filter的method过滤

时间:2019-04-05 12:24:32      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:field   eth   page   style   list   parser   rbac   object   lte   

1.View Demo

from django.shortcuts import render

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.parsers import JSONParser
from rest_framework import mixins, generics
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from goods.models import Goods, GoodsCategory
from goods.serializer import GoodsSerializer, CategorySerializer
from rest_framework import viewsets
from django_filters.rest_framework import DjangoFilterBackend

import django_filters
from rest_framework import filters
from django.db.models import Q


class GoodsFilter(django_filters.rest_framework.FilterSet):
    category_id = django_filters.rest_framework.NumberFilter(method=filter_catetory_id)

    def filter_catetory_id(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 = [category_id]


class GoodsList(mixins.ListModelMixin, viewsets.GenericViewSet):
    class GoodsPagination(PageNumberPagination):
        page_size = 2
        page_size_query_param = pageSize
        page_query_param = p
        max_page_size = 100

    queryset = Goods.objects.all()  # 不能切片后再过滤,例如:Goods.objects.all()[:10]
    serializer_class = GoodsSerializer
    pagination_class = GoodsPagination
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    search_fields = (=name,)  # 文档:https://www.django-rest-framework.org/api-guide/filtering/#searchfilter
    ordering_fields = (name,)
    # filter_fields = (‘name‘,) #逗号必加,缺点无法模糊查询
    filterset_class = GoodsFilter

2.SerializerDemo

class GoodsSerializer(serializers.ModelSerializer):
    """
    Goods的serializer
    """
    # 自定义,可以获取到外键数据
    # read_only表示只用在获取数据
    category_obj = CategorySerializer(source=category,read_only=True)
    category_name = serializers.CharField(source=category.name,read_only=True)
    class Meta:
        model = Goods
        # 外键写类里的名就可以
        # fields = (‘name‘,‘chick_num‘,‘category‘)
        fields = __all__

3.test

技术图片

 

django def django-filter的method过滤

标签:field   eth   page   style   list   parser   rbac   object   lte   

原文地址:https://www.cnblogs.com/chenyishi/p/10658201.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!