Django - 如何获取按属性值分组的查询集列表

时间:2015-01-21 20:28:16

标签: django

class MyObject(models.Model):
    type = models.CharField()

    def __unicode__(self):
        return self.type


#the type could be anything, its not predictable
MyObject.objects.create(type='a')
MyObject.objects.create(type='b')
MyObject.objects.create(type='c')
MyObject.objects.create(type='a')

是否可以检索按类型分组的查询集列表:

[[<MyObject: a>, <MyObject: a>], [<MyObject: b>], [<MyObject: c>]]

2 个答案:

答案 0 :(得分:6)

这是一种可能的方式:

grouped = dict()
for obj in MyObject.objects.all():
    grouped.setdefault(obj.type, []).append(obj)

这将产生一个像:

的字典
{'a': [<obj>, <obj>], 'b':[<obj>]}

答案 1 :(得分:2)

也许您需要itertools

groupby 之类的内容
 from itertools import groupby

 data = MyObject.objects.all()

 [list(result) for key, result  in groupby(data, key=lambda item: item['type'])]