Skip to content

Commit e1f7cc4

Browse files
authored
Minor refactoring of must_call_distinct (#4215)
1 parent 90bb0c5 commit e1f7cc4

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

rest_framework/filters.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -156,14 +156,15 @@ def construct_search(self, field_name):
156156
lookup = 'icontains'
157157
return LOOKUP_SEP.join([field_name, lookup])
158158

159-
def must_call_distinct(self, opts, lookups):
159+
def must_call_distinct(self, queryset, search_fields):
160160
"""
161161
Return True if 'distinct()' should be used to query the given lookups.
162162
"""
163-
for lookup in lookups:
164-
if lookup[0] in self.lookup_prefixes:
165-
lookup = lookup[1:]
166-
parts = lookup.split(LOOKUP_SEP)
163+
opts = queryset.model._meta
164+
for search_field in search_fields:
165+
if search_field[0] in self.lookup_prefixes:
166+
search_field = search_field[1:]
167+
parts = search_field.split(LOOKUP_SEP)
167168
for part in parts:
168169
field = opts.get_field(part)
169170
if hasattr(field, 'get_path_info'):
@@ -195,10 +196,11 @@ def filter_queryset(self, request, queryset, view):
195196
]
196197
queryset = queryset.filter(reduce(operator.or_, queries))
197198

198-
if self.must_call_distinct(queryset.model._meta, search_fields):
199+
if self.must_call_distinct(queryset, search_fields):
199200
# Filtering against a many-to-many field requires us to
200201
# call queryset.distinct() in order to avoid duplicate items
201202
# in the resulting queryset.
203+
# We try to avoid this is possible, for performance reasons.
202204
queryset = distinct(queryset, base)
203205
return queryset
204206

0 commit comments

Comments
 (0)