Skip to content

Commit

Permalink
Optimize database queries by deferring unnecessary fields in admin vi…
Browse files Browse the repository at this point in the history
…ews and context data
  • Loading branch information
AndersSeverinsen committed Dec 30, 2024
1 parent cbce7f9 commit 616ba08
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 7 deletions.
3 changes: 2 additions & 1 deletion bartab/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,8 @@ def count_consumption(admin, request):
def bartab_graph(admin, request):
balances = defaultdict(int)
graph_data = []
for snapshot in reversed(BarTabSnapshot.objects.all()):
bartab_snapshots = BarTabSnapshot.objects.defer("last_updated", "notes")
for snapshot in reversed(bartab_snapshots):
for entry in snapshot.entries.all():
balances[entry.user] += entry.added - entry.used

Expand Down
14 changes: 9 additions & 5 deletions bartenders/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,10 @@ class PollAdmin(admin.ModelAdmin):

@custom_admin_view("bartenders", "Bartender shift streaks")
def streaks_view(admin, request):
shifts = BartenderShift.objects.all().filter(end_datetime__lte=timezone.now())
bartender_shifts = BartenderShift.objects.defer(
"responsible", "other_bartenders", "period"
)
shifts = bartender_shifts.filter(end_datetime__lte=timezone.now())
shift_streaks = []
for shift in shifts:
shift_streaks.append(shift.streak())
Expand All @@ -248,10 +251,11 @@ def streaks_view(admin, request):
end_datetime__gte=timezone.now() - datetime.timedelta(days=5),
)
shift_placement = 0
for i, shift in enumerate(sorted_shift_streaks):
if shift[2] == current_shift[0].end_datetime:
shift_placement = i + 1
break
if current_shift:
for i, (streak, start_date, end_date) in enumerate(sorted_shift_streaks_short):
if end_date == current_shift[0].end_datetime:
shift_placement = i + 1
break

context = dict(
# Include common variables for rendering the admin template.
Expand Down
5 changes: 4 additions & 1 deletion web/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,10 @@ class About(TemplateView):

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
shifts = BartenderShift.objects.all().filter(end_datetime__lte=timezone.now())
bartender_shifts = BartenderShift.objects.defer(
"responsible", "other_bartenders", "period"
)
shifts = bartender_shifts.filter(end_datetime__lte=timezone.now())
current_shift = shifts.filter(
start_datetime__gte=timezone.now() - datetime.timedelta(days=7),
)
Expand Down

0 comments on commit 616ba08

Please sign in to comment.