Skip to content

Commit

Permalink
prefetching on character views to fix n+1 query issue
Browse files Browse the repository at this point in the history
  • Loading branch information
freyamade committed Jul 17, 2024
1 parent cca0476 commit 1de29a7
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
38 changes: 38 additions & 0 deletions backend/api/models/character.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,42 @@
RANDOM_CHARS = 30


class CharacterDetailsManager(models.Manager):

def with_summaries(self):
return self.prefetch_related('bis_lists', 'bis_lists__job')

def with_details(self):
return self.prefetch_related(
'bis_lists',
'bis_lists__bis_body',
'bis_lists__bis_bracelet',
'bis_lists__bis_earrings',
'bis_lists__bis_feet',
'bis_lists__bis_hands',
'bis_lists__bis_head',
'bis_lists__bis_left_ring',
'bis_lists__bis_legs',
'bis_lists__bis_mainhand',
'bis_lists__bis_necklace',
'bis_lists__bis_offhand',
'bis_lists__bis_right_ring',
'bis_lists__current_body',
'bis_lists__current_bracelet',
'bis_lists__current_earrings',
'bis_lists__current_feet',
'bis_lists__current_hands',
'bis_lists__current_head',
'bis_lists__current_left_ring',
'bis_lists__current_legs',
'bis_lists__current_mainhand',
'bis_lists__current_necklace',
'bis_lists__current_offhand',
'bis_lists__current_right_ring',
'bis_lists__job',
)


class Character(models.Model):
alias = models.CharField(max_length=64, default='')
avatar_url = models.URLField()
Expand All @@ -25,6 +61,8 @@ class Character(models.Model):
verified = models.BooleanField(default=False)
world = models.CharField(max_length=60)

objects = CharacterDetailsManager()

def __str__(self) -> str:
return self.display_name

Expand Down
4 changes: 2 additions & 2 deletions backend/api/views/character.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def get(self, request: Request) -> Response:
Retrieve all of the Characters belonging to the requesting User.
"""
# Permissions won't allow this method to be run by non-auth'd users
objs = Character.objects.filter(user=request.user)
objs = Character.objects.with_summaries().filter(user=request.user)
data = CharacterCollectionSerializer(objs, many=True).data
return Response(data)

Expand Down Expand Up @@ -92,7 +92,7 @@ def get(self, request: Request, pk: int) -> Response:
This endpoint will return the full data of the Character, including associated BISLists and Teams.
"""
try:
obj = Character.objects.get(pk=pk, user=request.user)
obj = Character.objects.with_details().get(pk=pk, user=request.user)
except Character.DoesNotExist:
return Response(status=404)

Expand Down

0 comments on commit 1de29a7

Please sign in to comment.