Skip to content

Commit

Permalink
perf: cache hearing for SectionViewSet and prefetch translations
Browse files Browse the repository at this point in the history
SectionViewSet shows the sections of a single hearing, thus hearing can
be cached to reduce number of duplicate queries as Model.get does not
evaluate lazily.

Refs: KER-250
  • Loading branch information
voneiden committed Oct 28, 2024
1 parent e37ed03 commit a958fd9
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions democracy/views/section.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from django.core.exceptions import ImproperlyConfigured
from django.db import transaction
from django.db.models import Max, Prefetch, Q
from django.utils.functional import cached_property
from django.utils.timezone import now
from django.views.generic import View
from django.views.generic.detail import SingleObjectMixin
Expand Down Expand Up @@ -434,19 +435,22 @@ class SectionViewSet(AdminsSeeUnpublishedMixin, viewsets.ReadOnlyModelViewSet):
serializer_class = SectionSerializer
model = Section

def get_queryset(self):
@cached_property
def hearing(self):
id_or_slug = self.kwargs["hearing_pk"]
hearing = Hearing.objects.get_by_id_or_slug(id_or_slug)
return Hearing.objects.get_by_id_or_slug(id_or_slug)

def get_queryset(self):
queryset = (
super()
.get_queryset()
.filter(hearing=hearing)
.filter(hearing=self.hearing)
.prefetch_related(
Prefetch("images", image_qs_for_request(self.request)),
Prefetch("images", image_qs_for_request(self.request).prefetch_related("translations")),
Prefetch("files", file_qs_for_request(self.request)),
)
)
if not hearing.closed:
if not self.hearing.closed:
queryset = queryset.exclude(type__identifier=InitialSectionType.CLOSURE_INFO)
return queryset

Expand Down Expand Up @@ -698,8 +702,8 @@ def get_queryset(self):
"translations",
"polls__translations",
"polls__options__translations",
Prefetch("images", image_qs_for_request(self.request)),
Prefetch("files", file_qs_for_request(self.request)),
Prefetch("images", image_qs_for_request(self.request).prefetch_related("translations")),
Prefetch("files", file_qs_for_request(self.request).prefetch_related("translations")),
)
)
queryset = filter_by_hearing_visible(queryset, self.request)
Expand Down

0 comments on commit a958fd9

Please sign in to comment.