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

Improve database queries to prevent 500 error on /users/watches #6516

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

smithellis
Copy link
Contributor

  • Use select_related and prefetch_related to avoid extra queries

* Use select and prefetch related to avoid extra queries
Copy link
Collaborator

@akatsoulas akatsoulas left a 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")
)
Copy link
Collaborator

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)

Copy link
Collaborator

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

Copy link
Contributor Author

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

Copy link
Contributor Author

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.

Copy link
Contributor Author

@smithellis smithellis Feb 21, 2025

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants