django UnboundLocalError:局部变量“current”在赋值前被引用

ygya80vv  于 2023-05-23  发布在  Go
关注(0)|答案(1)|浏览(162)

我使用django来聚合查询集的平均值,总和等,并有下面的代码。我所期望的是case匹配周期,然后在代码中进一步计算总和和平均值,但我得到了错误: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()

打印值,我得到:

# today:  2023-05-20
# weekday:  6
# month:  5
# year: 2023
# current week:  20

products_total是我模型中的一个字段,但我认为它与问题无关:

class Order(models.Model):
    products_total = models.DecimalField(max_digits=10, decimal_places=2, default=0.0)
    ...

我尝试使用if/elif语句,但得到相同的错误。
我也读过这个类似的问题,但不知道它是如何联系的,也不知道如何相应地编辑我的代码:UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
我错过了什么?

zpjtge22

zpjtge221#

period变量与match中的任何值都不匹配。这样current就永远不会被初始化,最终会出现这个错误。
您可以添加case _:,它将匹配不适合match中任何其他case的值。

相关问题