Skip to content

Commit

Permalink
Fixed N+1 query occurrence in the /api/v1/facility/
Browse files Browse the repository at this point in the history
Annotated the count of beds & patients in queryset

Fixes ohcnetwork#2256.
  • Loading branch information
dhruv-goyal-10 committed Jun 10, 2024
1 parent 37ab926 commit 6bc3d66
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
4 changes: 4 additions & 0 deletions care/facility/api/serializers/facility.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,13 @@ class FacilityBasicInfoSerializer(serializers.ModelSerializer):
bed_count = serializers.SerializerMethodField()

def get_bed_count(self, facility):
if hasattr(facility, "bed_count"):
return facility.bed_count
return Bed.objects.filter(facility=facility).count()

def get_patient_count(self, facility):
if hasattr(facility, "patient_count"):
return facility.patient_count
return PatientRegistration.objects.filter(
facility=facility, is_active=True
).count()
Expand Down
13 changes: 10 additions & 3 deletions care/facility/api/viewsets/facility.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.conf import settings
from django.db.models import Count, Q
from django_filters import rest_framework as filters
from djqscsv import render_to_csv_response
from drf_spectacular.utils import extend_schema, extend_schema_view
Expand Down Expand Up @@ -71,8 +72,15 @@ class FacilityViewSet(
):
"""Viewset for facility CRUD operations."""

queryset = Facility.objects.all().select_related(
"ward", "local_body", "district", "state"
queryset = (
Facility.objects.all()
.select_related("ward", "local_body", "district", "state")
.annotate(
bed_count=Count("bed"),
patient_count=Count(
"patientregistration", filter=Q(patientregistration__is_active=True)
),
)
)
permission_classes = (
IsAuthenticated,
Expand Down Expand Up @@ -147,7 +155,6 @@ def list(self, request, *args, **kwargs):
return render_to_csv_response(
queryset, field_header_map=mapping, field_serializer_map=pretty_mapping
)

return super(FacilityViewSet, self).list(request, *args, **kwargs)

@extend_schema(tags=["facility"])
Expand Down

0 comments on commit 6bc3d66

Please sign in to comment.