【发布时间】:2018-11-12 19:56:07
【问题描述】:
请不要重复我的问题,我已经搜索过它但没有一致的结果。 所以我正在用 djangorestframework 构建一个 restfull api
我想要这样的查询
http://localhost:8000/api/products/?category_name_fr=shirt,shoes
查找 category_name_fr 包含衬衫或鞋子的所有产品
为了在谷歌搜索后执行此操作,我编写了一个自定义 django 过滤器类(MultiValueCharFilter),但过滤器实际上并没有像我想要的那样运行。 当我进行上述查询时,它会返回 ProductTable 中的所有产品。但是当我进行如下查询时,过滤已正确完成
http://localhost:8000/api/products/?category_name_fr=shirt
这里是我的filters.py文件的源代码,产品类是ProductList
from django_filters import rest_framework as filters
from .models import ProductList
from django_filters import Filter
from django_filters.fields import Lookup
class MultiValueCharFilter(filters.BaseCSVFilter, filters.CharFilter):
def filter(self, qs, value):
# value is either a list or an 'empty' value
values = value or []
print(values)
for value in values:
qs = super(MultiValueCharFilter, self).filter(qs, value) | qs
return qs
class ProductListFilter(filters.FilterSet):
min_price = filters.NumberFilter(name="price", lookup_expr='gte')
max_price = filters.NumberFilter(name="price", lookup_expr='lte')
category_name_fr = MultiValueCharFilter(name="category_name_fr", lookup_expr='icontains')
category_name_en = MultiValueCharFilter(name="category_name_en", lookup_expr='icontains')
collection_name_fr = MultiValueCharFilter(name="collection_name_fr", lookup_expr='icontains')
collection_name_en = MultiValueCharFilter(name="collection_name_en", lookup_expr='icontains')
name_en = MultiValueCharFilter(name="name_en", lookup_expr='icontains')
name_fr = MultiValueCharFilter(name="name_fr", lookup_expr='icontains')
class Meta:
model = ProductList
fields = ['sale', 'sold', 'min_price', 'max_price', 'category_name_fr', 'name_en', 'name_fr',
'category_name_en', 'collection_name_fr', 'collection_name_en']
更多信息,这是视图 ListAPIView 的代码
from rest_framework import viewsets, generics, filters as rf_filters
from ..models import Product, Collection, ProductList
from ..serializers import ProductSerializer, CollectionSerializer, ProductListSerializer
from django_filters import rest_framework as filters
from ..filters import ProductFilter, ProductListFilter
from rest_framework.pagination import PageNumberPagination
from rest_framework.views import APIView
from rest_framework.response import Response
class StandardResultsSetPagination(PageNumberPagination):
page_size = 4
page_size_query_param = 'page_size'
max_page_size = 15
class ProductList(generics.ListAPIView):
queryset = ProductList.objects.all()
serializer_class = ProductListSerializer
filter_backends = (filters.DjangoFilterBackend,)
filter_class = ProductListFilter
serializer_class = ProductListSerializer
ordering_fields = ('price', 'created_at')
pagination_class = StandardResultsSetPagination
【问题讨论】:
标签: django django-models django-rest-framework