From 9892c8062bf64fb82f16eadebb2a9cbd093b9f32 Mon Sep 17 00:00:00 2001 From: Morten Madsen Lyngstad Date: Fri, 25 Jul 2025 08:10:38 +0200 Subject: [PATCH] Refactor logic to choose when analysis_orders are shown in the CSV and fix N + 1 query. --- src/genlab_bestilling/api/constants.py | 2 ++ src/genlab_bestilling/api/serializers.py | 11 +++++++++-- src/genlab_bestilling/api/views.py | 9 ++++++++- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/genlab_bestilling/api/constants.py b/src/genlab_bestilling/api/constants.py index a8189a3a..4b62197f 100644 --- a/src/genlab_bestilling/api/constants.py +++ b/src/genlab_bestilling/api/constants.py @@ -101,6 +101,8 @@ "genlab_id", "fish_id", "guid", + "order", + "analysis_orders", "river", "location.name", "under_locality", diff --git a/src/genlab_bestilling/api/serializers.py b/src/genlab_bestilling/api/serializers.py index 45740ab4..f5026e02 100644 --- a/src/genlab_bestilling/api/serializers.py +++ b/src/genlab_bestilling/api/serializers.py @@ -134,8 +134,15 @@ def get_fish_id(self, obj: Sample) -> str: return obj.fish_id or "-" def get_analysis_orders(self, obj: Sample) -> list[str]: - if obj.order and obj.order.analysis_orders.exists(): - return [str(anl.id) for anl in obj.order.analysis_orders.all()] + if not obj.order: + return [] + + analysis_orders = obj.order.analysis_orders.all() + # Return all analysis order IDs as strings + # only if there is exactly one analysis order, else return empty list. + # This is to ensure no duplicate rows in staffs common sheet + if analysis_orders.count() == 1: + return [str(analysis_orders.first().id)] return [] def get_project(self, obj: Sample) -> str: diff --git a/src/genlab_bestilling/api/views.py b/src/genlab_bestilling/api/views.py index e6b4965a..867b94dc 100644 --- a/src/genlab_bestilling/api/views.py +++ b/src/genlab_bestilling/api/views.py @@ -4,7 +4,7 @@ from typing import Any from django.db import transaction -from django.db.models import QuerySet +from django.db.models import Prefetch, QuerySet from django.http import HttpResponse from django.views import View from drf_spectacular.utils import extend_schema @@ -36,6 +36,7 @@ SpeciesFilter, ) from ..models import ( + AnalysisOrder, AnalysisType, ExtractionOrder, Location, @@ -190,6 +191,12 @@ def get_queryset(self) -> QuerySet: "order__genrequest__area", "location", ) + .prefetch_related( + Prefetch( + "order__analysis_orders", + queryset=AnalysisOrder.objects.only("id"), + ) + ) .order_by("genlab_id", "type") )