假设我有一个变量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)
在这种情况下,我已经传递了参数year
和month
in,因为time_period == 'monthly'
. 如果time_period == yearly
, 我只想通过year
, 如果time_period == weekly
, 我会通过所有三个 ( yearly
, monthly
, 和weekly
) 。
if
除了写 3 个陈述之外,有什么方法可以做我所描述的事情吗?