Skip to content

Commit 943935d

Browse files
committed
Refactor prefetching into a method on the queryset
1 parent c032b12 commit 943935d

File tree

2 files changed

+12
-17
lines changed

2 files changed

+12
-17
lines changed

readthedocs/core/templatetags/privacy_tags.py

+1-11
Original file line numberDiff line numberDiff line change
@@ -20,21 +20,11 @@ def is_admin(user, project):
2020

2121
@register.simple_tag(takes_context=True)
2222
def get_public_projects(context, user):
23-
# Creates a Subquery object which returns the latest builds 'id'.
24-
# Used for optimization purpose.
25-
subquery = Subquery(
26-
Build.objects.filter(
27-
project=OuterRef('project_id')).values_list('id', flat=True)[:1]
28-
)
29-
# Filters the latest builds of projects.
30-
latest_build = Prefetch('builds', Build.objects.filter(
31-
pk__in=subquery), to_attr=Project.LATEST_BUILD_CACHE
32-
)
3323
# 'Exists()' checks if the project has any good builds.
3424
projects = Project.objects.for_user_and_viewer(
3525
user=user,
3626
viewer=context['request'].user,
37-
).prefetch_related('users', latest_build).annotate(
27+
).prefetch_latest_build().annotate(
3828
_good_build=Exists(
3929
Build.objects.filter(success=True, project=OuterRef('pk')))
4030
)

readthedocs/projects/querysets.py

+11-6
Original file line numberDiff line numberDiff line change
@@ -75,14 +75,14 @@ def is_active(self, project):
7575

7676
return True
7777

78-
# Aliases
78+
def prefetch_latest_build(self):
79+
"""
80+
For a given queryset of projects, prefetch the latest build for each project
7981
80-
def dashboard(self, user=None):
81-
"""Get the projects for this user including the latest build"""
82+
This should come after any filtering.
83+
"""
8284
from readthedocs.builds.models import Build
8385

84-
projects = self.for_admin_user(user)
85-
8686
# Prefetch the latest build for each project.
8787
subquery = Subquery(
8888
Build.objects.filter(project=OuterRef('project_id')).values_list('id', flat=True)[:1]
@@ -92,8 +92,13 @@ def dashboard(self, user=None):
9292
Build.objects.filter(pk__in=subquery),
9393
to_attr=self.model.LATEST_BUILD_CACHE,
9494
)
95+
return self.prefetch_related(latest_build)
96+
97+
# Aliases
9598

96-
return projects.prefetch_related(latest_build)
99+
def dashboard(self, user=None):
100+
"""Get the projects for this user including the latest build"""
101+
return self.for_admin_user(user).prefetch_latest_build()
97102

98103
def api(self, user=None, detail=True):
99104
if detail:

0 commit comments

Comments
 (0)