django-filter
django-filter copied to clipboard
Multifield filtering on related models does not work as expected
For this filterset:
class UserJobFilterSet(filters.FilterSet):
field1 = filters.CharFilter('users_statuses__field1')
field2 = filters.CharFilter('users_statuses__field1')
If both field1
and field2
provided it will not work as expected (AND operation) for reasons described here https://docs.djangoproject.com/en/2.2/topics/db/queries/#spanning-multi-valued-relationships and here https://stackoverflow.com/questions/8164675/chaining-multiple-filter-in-django-is-this-a-bug/8164920
To fix it this method:
def filter_queryset(self, queryset):
for name, value in self.form.cleaned_data.items():
queryset = self.filters[name].filter(queryset, value)
return queryset
should be reimplemented into collecting kwargs and submitting them in a single filter()
call instead of nesting filter()
calls.
#745 is related. The short answer is that collecting kwargs or Q-objects isn't a workable solution, since it would break many types of filters. e.g., the OrderingFilter
or any filter that should exclude
instead of filter
.
One workaround is to call qs._next_is_sticky()
in the loop.
+1