0

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?

alkadelik
  • 526
  • 1
  • 7
  • 18

1 Answers1

1

the period variable does not match any of the values in your match. That way current will never get initialized and you end up with this error.

You can add case _: which will match the values not fitting into any of the other case in the match.

yedpodtrzitko
  • 9,035
  • 2
  • 40
  • 42
  • Thanks. I have a follow up question in the link below. Can you please help: https://stackoverflow.com/questions/76294456/django-template-response-contentnotrenderederror-the-response-content-must-be-r – alkadelik May 20 '23 at 09:31