2012-03-13 43 views
1

我保存的待辦事項隨着時間的量的估計值的Django的模型將需要完成每一個:獲得第一個MySQL數據庫記錄了總和爲特定值

class Action(models.Model): 
    name = models.CharField("Action Name", max_length=200, unique = True) 
    complete = models.BooleanField(default=False, verbose_name="Complete?") 
    creation_date = models.DateTimeField("Creation Date", default=datetime.now) 
    time_estimate = models.IntegerField("Estimated Completion Time", choices = TIME_ESTIMATES, default = 15) 

我想查詢由creation_date排序的所有不完整動作,以獲取總計time_estimate不超過一定數量的動作。

所以我們可以說我有5個動作:

Name: Action 1 
time_estimate: 10 

Name: Action 2 
time_estimate: 20 

Name: Action 3 
time_estimate: 30 

Name: Action 4 
time_estimate: 40 

Name: Action 5 
time_estimate: 50 

假設它們的順序排序,我得到了55分鐘的時間,我希望該過濾器返回操作1和2。如果我有100分鐘,我想讓過濾器返回操作1,2,3和4.

可以這樣做嗎?

回答

0

有可能是一個更優雅的方式,但我可能會做一個循環,直到超過此值總時間相加:

time_allowed = 55 
time_used = 0 
actions = [] 

for a in Action.objects.filter(complete=False).order_by('creation_date'): 
    if time_used + a.time_estimate <= time_allowed: 
     time_used += a.time_estimate 
     actions.append(a) 

# actions is a list of actions which can be accomplished within the 
# time_allowed threshhold, and you can loop them to display, or whatever you 
# are trying to do with them. 

如果你想讓它更可擴展性,可以通過time_estimate訂購( ASC),並添加一個else語句以在超過time_allowed時中斷for循環。像這樣:

time_allowed = 55 
time_used = 0 
actions = [] 

for a in Action.objects.filter(complete=False).order_by('time_estimate', 'creation_date'): 
    if time_used + a.time_estimate <= time_allowed: 
     time_used += a.time_estimate 
     actions.append(a) 
    else: 
     break 
+0

甜。我甚至沒有想到它會繼續添加任務,直到time_used儘可能接近time_allowed。謝謝。 – 2012-03-13 19:50:47

相關問題