2012-08-14 40 views
1

比方说,我有一个变量time_period,其值为以下字符串之一:weeklymonthly,yearly根据参数简化QuerySet调用

...和一个QuerySet呼叫通过模型TimeModel过滤:

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

在这种情况下,我传递的参数yearmonth,因为time_period == 'monthly'。如果time_period == yearly,我只想通过year,如果time_period == weekly,我会通过这三个(yearlymonthlyweekly)英寸

有什么我已经写3 if的描述短做的任何方式声明?

回答

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) 
+0

我得到'语法错误:关键字arg'后非关键字ARG。然而,在QuerySet调用之外调用time_periods ['monthly']会正确调出一个'Q'对象。 – 2012-08-14 05:28:01

+0

通过切换两个参数的顺序来修复它。我会继续编辑您的帖子。 – 2012-08-14 22:12:57