From 4e8f825eed37c2754ae0df2d747df2786fb8ea4f Mon Sep 17 00:00:00 2001 From: Matti Lamppu Date: Mon, 16 Dec 2024 11:40:44 +0200 Subject: [PATCH] Add "has_reservations" field to application section model --- .../graphql/types/application_section/types.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/tilavarauspalvelu/api/graphql/types/application_section/types.py b/tilavarauspalvelu/api/graphql/types/application_section/types.py index 22b453861..b3eb6e54d 100644 --- a/tilavarauspalvelu/api/graphql/types/application_section/types.py +++ b/tilavarauspalvelu/api/graphql/types/application_section/types.py @@ -6,11 +6,11 @@ from django.db import models from graphene_django_extensions import DjangoNode from lookup_property import L -from query_optimizer import AnnotatedField +from query_optimizer import AnnotatedField, ManuallyOptimizedField from query_optimizer.optimizer import QueryOptimizer from tilavarauspalvelu.enums import ApplicationSectionStatusChoice, UserRoleChoice -from tilavarauspalvelu.models import Application, ApplicationSection, User +from tilavarauspalvelu.models import Application, ApplicationSection, Reservation, User from .filtersets import ApplicationSectionFilterSet from .permissions import ApplicationSectionPermission @@ -25,6 +25,8 @@ class ApplicationSectionNode(DjangoNode): status = AnnotatedField(graphene.Enum.from_enum(ApplicationSectionStatusChoice), expression=L("status")) allocations = AnnotatedField(graphene.Int, expression=L("allocations")) + has_reservations = ManuallyOptimizedField(graphene.Boolean, required=True) + class Meta: model = ApplicationSection fields = [ @@ -101,3 +103,15 @@ def pre_optimization_hook(cls, queryset: ApplicationSectionQuerySet, optimizer: @classmethod def _add_units_for_permissions(cls, queryset: ApplicationQuerySet, *args: Any) -> models.QuerySet: return queryset.with_permissions() + + @staticmethod + def optimize_has_reservations(queryset: models.QuerySet, optimizer: QueryOptimizer) -> models.QuerySet: + optimizer.annotations["has_reservations"] = models.Exists( + Reservation.objects.filter( + recurring_reservation__allocated_time_slot__reservation_unit_option__application_section=( + models.OuterRef("pk") + ), + ) + ) + + return queryset