DRF - is it possible to combine multiple filter parameters in the URL with some kind of OR logical symbol
Unfortunately, it's not possible with the current django_filter
implementation. Every single filter modifies the queryset in-place instead of returning the Q
object, which could be joined to your taste. You could try overriding the FilterSet.qs()
method and doing some black magic on self._qs.query.where
to recombine clauses using OR
. See also a question on editing the queryset filters.
Update: As long as Django handles SQL injection attempts really well, you could just use something like:
qs.filter(map(operators.or_, [Q(k=v) for k, v in request.GET.items()]))
, but surely it needs some validation before putting it to production.
I also wanted to do something similar to this and ended up creating a custom filter using django-filter to do it, hope this helps:
class NameFilter(django_filters.CharFilter):
def filter(self, qs, value):
if value:
return qs.filter(Q(**{first_name+'__'+self.lookup_expr: value}) |
Q(**{last_name+'__'+self.lookup_expr: value}))
return qs
class PersonFilter(django_filters.rest_framework.FilterSet):
name = NameFilter(lookup_expr='icontains')
/api/rest/v1/Person?name=foo&page_size=10
not a very generic solution but it is an example of how to create your own filters, how generic it is depends on your code implementation.