diff --git a/readthedocs/projects/views/private.py b/readthedocs/projects/views/private.py index b23a4ef3654..8ef7570ebfe 100644 --- a/readthedocs/projects/views/private.py +++ b/readthedocs/projects/views/private.py @@ -6,7 +6,7 @@ from allauth.socialaccount.models import SocialAccount from django.conf import settings from django.contrib import messages -from django.db.models import Count +from django.db.models import Count, OuterRef, Subquery from django.http import ( Http404, HttpResponseBadRequest, @@ -39,10 +39,7 @@ Version, VersionAutomationRule, ) -from readthedocs.core.mixins import ( - ListViewWithForm, - PrivateViewMixin, -) +from readthedocs.core.mixins import ListViewWithForm, PrivateViewMixin from readthedocs.core.utils import broadcast, trigger_build from readthedocs.core.utils.extend import SettingsOverrideObject from readthedocs.integrations.models import HttpExchange, Integration @@ -996,18 +993,21 @@ def get_context_data(self, **kwargs): project.slug, ) - queries = [] - qs = SearchQuery.objects.filter(project=project) - if qs.exists(): - qs = ( - qs.values('query') - .annotate(count=Count('id')) - .order_by('-count', 'query') - .values_list('query', 'count', 'total_results') + project_queries = SearchQuery.objects.filter(project=project) + last_total_results = ( + project_queries.filter(query=OuterRef('query')) + .order_by('-modified') + .values('total_results') + ) + queries = ( + project_queries.values('query') + .annotate( + count=Count('id'), + total_results=Subquery(last_total_results[:1]) ) - - # only show top 100 queries - queries = qs[:100] + .order_by('-count', 'query') + .values_list('query', 'count', 'total_results') + )[:100] context.update( {