2012-08-14 73 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