1

假设我有一个变量time_period,其值为以下字符串之一:weekly, monthly, yearly

...以及通过模型过滤的 QuerySet 调用TimeModel

time_period = 'monthly'
instance = TimeModel.objects.get(time_period=time_period,
                                 year=datetime.now().year,
                                 month=datetime.now().month)

在这种情况下,我已经传递了参数yearmonthin,因为time_period == 'monthly'. 如果time_period == yearly, 我只想通过year, 如果time_period == weekly, 我会通过所有三个 ( yearly, monthly, 和weekly) 。

if除了写 3 个陈述之外,有什么方法可以做我所描述的事情吗?

4

1 回答 1

2

也许这有帮助:

from django.db.models import Q

now = datetime.now()
time_periods = {
    'weekly': Q(year=now.year, month=now.month, day=now.week),  # note from OP: now.week is technically invalid; you actually want to use now.isocalendar()[1]
    'monthly': Q(year=now.year, month=now.month),
    'yearly': Q(year=now.year),
}

instance = TimeModel.objects.get(time_periods[time_period], time_period=time_period)
于 2012-08-14T05:10:39.200 回答