Solve Django Filter queryset result duplicates with Pagination


When we filter using multiple filter and mixed with django pagination, somehow the results are duplicates. This is incorrect. Apparently, looking at the source code https://github.com/alex/django-filter/blob/master/django_filters/filters.py#L105, I found this line:

1
2
3
4
q = Q()
for v in value:
    q |= Q(**{self.name: v})
return qs.filter(q).distinct()

By default, django-filter not using “AND” condition and that’s why it’s showing duplicates.

To fix this, then we can use distinct when passing object_list in paginator, example:

1
results = paginator(request, PlanningOrder, ‘farmseason’, object_list.qs.distinct())

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.