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

Fixes #8715: eliminates duplicates when used in many-to-many field constraints #8793

Merged
merged 1 commit into from
Mar 7, 2022
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
6 changes: 6 additions & 0 deletions netbox/utilities/querysets.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ def restrict(self, user, action='view'):
# Any permission with null constraints grants access to _all_ instances
attrs = Q()
break
else:
# for else, when no break
# avoid duplicates when JOIN on many-to-many fields without using DISTINCT.
# DISTINCT acts globally on the entire request, which may not be desirable.
allowed_objects = self.model.objects.filter(attrs)
attrs = Q(pk__in=allowed_objects)
Comment on lines +46 to +47
Copy link
Member

Choose a reason for hiding this comment

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

This approach can be optimized by retrieving only the IDs list (rather than a full queryset) in the first query.

Suggested change
allowed_objects = self.model.objects.filter(attrs)
attrs = Q(pk__in=allowed_objects)
allowed_object_ids = self.model.objects.filter(attrs).values_list('pk', flat=True)
attrs = Q(pk__in=allowed_object_ids)

qs = self.filter(attrs)

return qs