I'm using django to aggregate averages, sums, etc, of a queryset and have the code below. What I expect is that the case matches the period and then the sum and average is computed further down the code but I get the error: UnboundLocalError: local variable 'current' referenced before assignment
def metrics(request):
email = request.data.get("email")
period = request.data.get("period") # [0,1,2,3 : day, week, month, year]
today = date.today()
weekday = date.isoweekday(today)
month = today.month
year = today.year
current_week = date.isocalendar(today).week
store = Store.objects.get(account__email=email)
sales = Order.objects.filter(store=store)
match period:
case 0:
# 'Today'
current = sales.filter(created__week_day=weekday)
past = sales.filter(created__week_day=weekday - 1)
case 1:
# 'This week'
current = sales.filter(created__week=current_week)
past = sales.filter(created__week=current_week - 1)
case 2:
# 'This month'
current = sales.filter(created__month=month)
past = sales.filter(created__month=month - 1)
case 3:
# 'This year'
current = sales.filter(created__year=year)
past = sales.filter(created__year=year - 1)
current_total = current.aggregate(Sum('products_total'))['products_total__sum']
past_total = past.aggregate(Sum('products_total'))['products_total__sum']
current_average = current.aggregate(Avg('products_total'))['products_total__avg']
past_average = past.aggregate(Avg('products_total'))['products_total__avg']
current_count = current.count()
past_count = past.count()
Printing the values, I get:
# today: 2023-05-20
# weekday: 6
# month: 5
# year: 2023
# current week: 20
products_total is a field in my model but I don't think is relevant to the question:
class Order(models.Model):
products_total = models.DecimalField(max_digits=10, decimal_places=2, default=0.0)
...
I've tried using if/elif
statements but get the same error.
I've also read through this similar question but can't see how it relates or how to edit my code accordingly: UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
What am I missing?