Skip to content

Commit 8a38991

Browse files
authored
Fix SearchFilter.must_call_distinict for annotation+m2m (encode#7146)
* Test SearchFilter annotation+m2m distinct * Fix SearchFilter annotation+m2m distinct
1 parent 4ac0fae commit 8a38991

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

rest_framework/filters.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def must_call_distinct(self, queryset, search_fields):
8585
search_field = search_field[1:]
8686
# Annotated fields do not need to be distinct
8787
if isinstance(queryset, models.QuerySet) and search_field in queryset.query.annotations:
88-
return False
88+
continue
8989
parts = search_field.split(LOOKUP_SEP)
9090
for part in parts:
9191
field = opts.get_field(part)

tests/test_filters.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,21 @@ class SearchListView(generics.ListAPIView):
406406
assert len(response.data) == 1
407407
assert response.data[0]['title_text'] == 'ABCDEF'
408408

409+
def test_must_call_distinct_subsequent_m2m_fields(self):
410+
f = filters.SearchFilter()
411+
412+
queryset = SearchFilterModelM2M.objects.annotate(
413+
title_text=Upper(
414+
Concat(models.F('title'), models.F('text'))
415+
)
416+
).all()
417+
418+
# Sanity check that m2m must call distinct
419+
assert f.must_call_distinct(queryset, ['attributes'])
420+
421+
# Annotated field should not prevent m2m must call distinct
422+
assert f.must_call_distinct(queryset, ['title_text', 'attributes'])
423+
409424

410425
class OrderingFilterModel(models.Model):
411426
title = models.CharField(max_length=20, verbose_name='verbose title')

0 commit comments

Comments
 (0)