Skip to content

Commit 6661035

Browse files
tag based filtering: avoid duplicate rows in results (#13442)
* tag based filtering: avoid duplicate rows in results * tag based filtering: avoid duplicate rows in results * improvements
1 parent a09cfc6 commit 6661035

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

dojo/filters.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,34 @@ def __init__(self, *args, **kwargs):
354354
if exclude:
355355
self.form.fields[field].label = "Not " + self.form.fields[field].label
356356

357+
def filter_queryset(self, queryset):
358+
qs = super().filter_queryset(queryset)
359+
if hasattr(self, "form") and hasattr(self.form, "cleaned_data"):
360+
for name, f in self.filters.items():
361+
field_name = getattr(f, "field_name", "") or ""
362+
# Only apply distinct for tag lookups that can duplicate base rows
363+
if "tags__name" in field_name:
364+
value = self.form.cleaned_data.get(name, None)
365+
if value not in (None, "", [], (), {}):
366+
lookup_expr = getattr(f, "lookup_expr", None)
367+
is_exclude = getattr(f, "exclude", False)
368+
needs_distinct = (
369+
is_exclude
370+
or lookup_expr in {
371+
"in",
372+
"contains",
373+
"icontains",
374+
"startswith",
375+
"istartswith",
376+
"endswith",
377+
"iendswith",
378+
}
379+
)
380+
# exact/iexact typically won't duplicate rows
381+
if needs_distinct:
382+
return qs.distinct()
383+
return qs
384+
357385

358386
def get_tags_model_from_field_name(field):
359387
exclude = False

0 commit comments

Comments
 (0)