如何提取具有最大值的django对象?

时间:2017-05-13 05:52:11

标签: python mysql django python-2.7

假设我有一个django模型:

class Score(models.Model):
    name = models.CharField(max_length=32)
    value = models.IntegerField()
    status = models.BooleanField()

    def __unicode__(self):
        return u"{}: {} {}".format(self.name, self.value, self.status)

表格score看起来像这样:

id | name  | value | status
---+-------+-------+-------
1  | john  | 15    | 0
2  | ivan  | 21    | 0
3  | david | 14    | 1
4  | john  | 11    | 1
5  | john  | 25    | 0
6  | david | 8     | 1

我想为每个名称提取最大value的对象作为名称列表。例如:

names = ['john', 'david', 'paul']

dct = process(names) # How to implement this function???

for name, obj in dct.items():
    print name, obj

应打印:

john john: 25 False
david david: 14 True
paul None

表现很重要。我应该在score处理大约1k个名称,每个名称大约有1k个记录。使用django最好的方法是什么?在这个任务中使用django ORM是否有意义?

我使用MySQL数据库。

感谢您提前。

1 个答案:

答案 0 :(得分:0)

解决方案:

def process(names):
    # Finding max scores
    result = Score.objects.filter(name__in=names).\
        values('name').annotate(Max('value'))

    value_max_items = set(
        row['value__max']
        for row in result
    )

    # Query for objects having max scores
    result = Score.objects.filter(value__in=value_max_items)

    # Creating dct
    dct = {}
    for obj in result:
        if obj.name not in dct or obj.value > dct[obj.name].value:
            dct[obj.name] = obj

    # If some names missed, set None for them
    for name in names:
        if name not in dct:
            dct[name] = None

    return dct