Skip to content

Commit a6e1fde

Browse files
authored
Add support for successful build prefetch (#11613)
We use both latest build and latest successful build in the project listing template.
1 parent e5f8092 commit a6e1fde

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

readthedocs/projects/models.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,7 @@ class Project(models.Model):
575575

576576
# Property used for storing the latest build for a project when prefetching
577577
LATEST_BUILD_CACHE = "_latest_build"
578+
LATEST_SUCCESSFUL_BUILD_CACHE = "_latest_successful_build"
578579

579580
class Meta:
580581
ordering = ("slug",)
@@ -920,6 +921,13 @@ def conf_dir(self, version=LATEST):
920921

921922
@property
922923
def has_good_build(self):
924+
# Check if there is `_latest_successful_build` attribute in the Queryset.
925+
# Used for database optimization.
926+
if hasattr(self, self.LATEST_SUCCESSFUL_BUILD_CACHE):
927+
if build_successful := getattr(self, self.LATEST_SUCCESSFUL_BUILD_CACHE):
928+
return build_successful[0]
929+
return None
930+
923931
# Check if there is `_good_build` annotation in the Queryset.
924932
# Used for Database optimization.
925933
if hasattr(self, "_good_build"):

readthedocs/projects/querysets.py

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -132,17 +132,33 @@ def prefetch_latest_build(self):
132132
from readthedocs.builds.models import Build
133133

134134
# Prefetch the latest build for each project.
135-
subquery = Subquery(
135+
subquery_build_latest = Subquery(
136136
Build.internal.filter(project=OuterRef("project_id"))
137137
.order_by("-date")
138138
.values_list("id", flat=True)[:1]
139139
)
140-
latest_build = Prefetch(
140+
prefetch_build_latest = Prefetch(
141141
"builds",
142-
Build.internal.filter(pk__in=subquery),
142+
Build.internal.filter(pk__in=subquery_build_latest),
143143
to_attr=self.model.LATEST_BUILD_CACHE,
144144
)
145-
return self.prefetch_related(latest_build)
145+
146+
# Prefetch the latest successful build for each project.
147+
subquery_build_successful = Subquery(
148+
Build.internal.filter(project=OuterRef("project_id"))
149+
.order_by("-date")
150+
.values_list("id", flat=True)[:1]
151+
)
152+
prefetch_build_successful = Prefetch(
153+
"builds",
154+
Build.internal.filter(pk__in=subquery_build_successful),
155+
to_attr=self.model.LATEST_SUCCESSFUL_BUILD_CACHE,
156+
)
157+
158+
return self.prefetch_related(
159+
prefetch_build_latest,
160+
prefetch_build_successful,
161+
)
146162

147163
# Aliases
148164

0 commit comments

Comments
 (0)