如果我需要在django休息中进行过滤,那么我通常会这样做
class ProductFilter(django_filters.FilterSet):
min_price = django_filters.NumberFilter(name="price", lookup_type='gte')
max_price = django_filters.NumberFilter(name="price", lookup_type='lte')
class Meta:
model = Product
fields = ['category', 'in_stock', 'min_price', 'max_price']
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_class = ProductFilter
我可以像
一样使用 http://example.com/api/products?category=clothing&max_price=10.00
但这会AND
我怎么能这样做或者从网址
其中(category = clothing || max_price = 10)
基本上我应该能够提供URL中的所有参数,如
http://example.com/api/products? AND=[{category: clothing}, {age: 10}], OR=[{age_gte:10}]
答案 0 :(得分:2)
Okey,你需要在你的url中传入一些标志来检查你是否要执行混合查询。同时为params添加前缀,如果在AND运算符中应使用age=20
,则添加前缀'and_',它看起来像and_age=20
,依此类推。 OR params也是如此。
让我们有这个网址
http://example.com/api/products?and_category=clothing&and_max_price=10.00&or_age=20&mixed=true
现在,我们的观点。
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_class = ProductFilter
def get_queryset(self):
data = self.request.DATA
mixed_query = data.get('mixed',None)
if not mixed_query:
return self.queryset
and_params = {}
for key in data:
if 'and_' in key:
and_params[key] = data[key]
queryset = Products.objects.filter(**and_params)
for key in self.request.DATA:
if 'or_' in key:
queryset = queryset | Products.objects.filter(key=data[key])
return queryset