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

Minor refactoring of must_call_distinct #4215

Merged
merged 1 commit into from
Jun 23, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions rest_framework/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,14 +156,15 @@ def construct_search(self, field_name):
lookup = 'icontains'
return LOOKUP_SEP.join([field_name, lookup])

def must_call_distinct(self, opts, lookups):
def must_call_distinct(self, queryset, search_fields):
"""
Return True if 'distinct()' should be used to query the given lookups.
"""
for lookup in lookups:
if lookup[0] in self.lookup_prefixes:
lookup = lookup[1:]
parts = lookup.split(LOOKUP_SEP)
opts = queryset.model._meta
for search_field in search_fields:
if search_field[0] in self.lookup_prefixes:
search_field = search_field[1:]
parts = search_field.split(LOOKUP_SEP)
for part in parts:
field = opts.get_field(part)
if hasattr(field, 'get_path_info'):
Expand Down Expand Up @@ -195,10 +196,11 @@ def filter_queryset(self, request, queryset, view):
]
queryset = queryset.filter(reduce(operator.or_, queries))

if self.must_call_distinct(queryset.model._meta, search_fields):
if self.must_call_distinct(queryset, search_fields):
# Filtering against a many-to-many field requires us to
# call queryset.distinct() in order to avoid duplicate items
# in the resulting queryset.
# We try to avoid this is possible, for performance reasons.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We try to avoid this if possible, for performance reasons.

queryset = distinct(queryset, base)
return queryset

Expand Down