获取第一个汇总到特定值的mysql数据库记录

时间:2012-03-13 16:52:11

标签: mysql django filter django-filters

我有一个Django模型,它持有待办事项,估计完成每个模型所需的时间:

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。

可以这样做吗?

1 个答案:

答案 0 :(得分: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)进行排序,并在超出time_allowed时添加else语句来中断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