-
Notifications
You must be signed in to change notification settings - Fork 750
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
Improve database queries to prevent 500 error on /users/watches #6516
base: main
Are you sure you want to change the base?
Conversation
* Use select and prefetch related to avoid extra queries
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
r+wc
.select_related("content_type") | ||
.prefetch_related("content_object") | ||
.order_by("content_type", "id") | ||
) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Probably is more efficient to exclude from fetching items that you don't care about.
watches = (
Watch.objects.filter(
user=request.user
)
.exclude(content_object__isnull=True)
.exclude(Q(content_type__model="question") & Q(content_object__is_archived=True))
.select_related("content_type")
.prefetch_related("content_object")
.order_by("content_type", "id")
)
watch_list = paginate(request, watches)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the reason for the Q object is to ensure that it will filter out is_archived
attributes only for questions. Otherwise it will potentially raise AttributeError for content_types that don't have that attribute defined in their model
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's a good catch. Thanks @akatsoulas
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can't filter on the GenericForeignKey
field content_object
since it can't automatically generate a reverse. I'm working on a fix.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I also noticed a potential issue with the POST content making multiple saves vs. a single bulk update, and altered that.
ff26779
to
20a6de9
Compare
20a6de9
to
e2c25af
Compare
select_related
andprefetch_related
to avoid extra queries