Skip to content

Commit

Permalink
Fix multiple user queries n+1 issue
Browse files Browse the repository at this point in the history
  • Loading branch information
szabozoltan69 committed Jul 1, 2024
1 parent 9c69de1 commit f7a0bb3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
20 changes: 18 additions & 2 deletions api/drf_views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from datetime import timedelta

from django.contrib.auth.models import User
from django.contrib.auth.models import Group, User
from django.db import models
from django.db.models import (
Avg,
Expand Down Expand Up @@ -1297,7 +1297,23 @@ class UsersViewset(viewsets.ReadOnlyModelViewSet):
filterset_class = UserFilterSet

def get_queryset(self):
return User.objects.filter(is_active=True)

return (
User.objects.select_related(
"profile",
"profile__country",
)
.prefetch_related("subscription")
.annotate(
is_ifrc_admin=models.Exists(
Group.objects.filter(
name__iexact="IFRC Admins",
user=OuterRef("pk"),
)
)
)
.filter(is_active=True)
)


class GlobalEnumView(APIView):
Expand Down
9 changes: 5 additions & 4 deletions api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1616,7 +1616,7 @@ class Meta:
class UserSerializer(ModelSerializer):
profile = ProfileSerializer()
subscription = MiniSubscriptionSerializer(many=True)
is_ifrc_admin = serializers.SerializerMethodField()
is_ifrc_admin = serializers.BooleanField(read_only=True)

class Meta:
model = User
Expand Down Expand Up @@ -1654,9 +1654,10 @@ def update(self, instance, validated_data):
instance.save()
return instance

@staticmethod
def get_is_ifrc_admin(obj) -> bool:
return obj.groups.filter(name__iexact="IFRC Admins").exists()
# Instead of the below method we use the serializer's annotate tag:
# @staticmethod
# def get_is_ifrc_admin(obj) -> bool:
# return obj.groups.filter(name__iexact="IFRC Admins").exists()


class UserNameSerializer(UserSerializer):
Expand Down

0 comments on commit f7a0bb3

Please sign in to comment.