How can i make OR operator in query params in django rest framework
If i need to do filtering in django rest then i usually do this
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
I can use like
http://example.com/api/products?category=clothing&max_price=10.00
But this will do AND
How can i do that OR from url like
where (category = clothing || max_price = 10)
Basically i should be able to provide all params in URL like
http://example.com/api/products? AND=[{category: clothing}, {age: 10}], OR=[{age_gte:10}]
Okey, you need to pass in your url some flag to check if you want to perform a mixed query. Also add a prefix to params, if age=20
should be used in the AND operator, add prefix 'and_', it looks like and_age=20
and so on. The same for OR params.
Let's have this url
http://example.com/api/products?and_category=clothing&and_max_price=10.00&or_age=20&mixed=true
Now, our view.
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
NOTE: request.DATA
has been deprecated in favor of request.data
since version 3.0