Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix SearchFilter.must_call_distinict for annotation+m2m #7146

Merged
merged 2 commits into from May 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion rest_framework/filters.py
Expand Up @@ -86,7 +86,7 @@ def must_call_distinct(self, queryset, search_fields):
search_field = search_field[1:]
# Annotated fields do not need to be distinct
if isinstance(queryset, models.QuerySet) and search_field in queryset.query.annotations:
return False
continue
parts = search_field.split(LOOKUP_SEP)
for part in parts:
field = opts.get_field(part)
Expand Down
15 changes: 15 additions & 0 deletions tests/test_filters.py
Expand Up @@ -368,6 +368,21 @@ class SearchListView(generics.ListAPIView):
assert len(response.data) == 1
assert response.data[0]['title_text'] == 'ABCDEF'

def test_must_call_distinct_subsequent_m2m_fields(self):
f = filters.SearchFilter()

queryset = SearchFilterModelM2M.objects.annotate(
title_text=Upper(
Concat(models.F('title'), models.F('text'))
)
).all()

# Sanity check that m2m must call distinct
assert f.must_call_distinct(queryset, ['attributes'])

# Annotated field should not prevent m2m must call distinct
assert f.must_call_distinct(queryset, ['title_text', 'attributes'])


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