django-filter icon indicating copy to clipboard operation
django-filter copied to clipboard

Multifield filtering on related models does not work as expected

Open dmugtasimov opened this issue 5 years ago • 2 comments

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.

dmugtasimov avatar May 09 '19 19:05 dmugtasimov

#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.

rpkilby avatar May 09 '19 20:05 rpkilby

+1

rubbish822 avatar May 10 '19 08:05 rubbish822