From bc41a71219bd6b23dff5823eb9b434e61b6bd733 Mon Sep 17 00:00:00 2001 From: Tanner Collin Date: Mon, 27 Mar 2023 18:45:52 +0000 Subject: [PATCH] Reduce /user/ queries with select and prefetch related --- apiserver/apiserver/api/serializers.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/apiserver/apiserver/api/serializers.py b/apiserver/apiserver/api/serializers.py index 8deecb2..e770d01 100644 --- a/apiserver/apiserver/api/serializers.py +++ b/apiserver/apiserver/api/serializers.py @@ -713,6 +713,7 @@ class UserSerializer(serializers.ModelSerializer): training = UserTrainingSerializer(many=True) member = MemberSerializer() transactions = serializers.SerializerMethodField() + training = serializers.SerializerMethodField() interests = InterestSerializer(many=True) door_code = serializers.SerializerMethodField() wifi_pass = serializers.SerializerMethodField() @@ -738,12 +739,27 @@ class UserSerializer(serializers.ModelSerializer): def get_transactions(self, obj): queryset = models.Transaction.objects.filter(user=obj) + queryset = queryset.select_related('user', 'user__member') queryset = queryset.exclude(category='Memberships:Fake Months') queryset = queryset.order_by('-id', '-date') serializer = TransactionSerializer(data=queryset, many=True) serializer.is_valid() return serializer.data + def get_training(self, obj): + queryset = obj.training + queryset = queryset.select_related( + 'session', + 'session__course', + 'session__instructor', + 'session__instructor__member' + ) + queryset = queryset.prefetch_related('session__students') + queryset = queryset.order_by('-id') + serializer = UserTrainingSerializer(data=queryset, many=True) + serializer.is_valid() + return serializer.data + def get_door_code(self, obj): if not obj.member.paused_date and obj.cards.count(): return secrets.DOOR_CODE