Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - How to get a list of queryset grouped by attribute value

Tags:

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')

Is it possible to retrieve a list of queryset grouped by the type like that:

[[<MyObject: a>, <MyObject: a>], [<MyObject: b>], [<MyObject: c>]]
like image 761
Below the Radar Avatar asked Jan 21 '15 20:01

Below the Radar


2 Answers

Here's one possible way:

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

That will yield a dict like:

{'a': [<obj>, <obj>], 'b':[<obj>]}
like image 132
dylrei Avatar answered Nov 17 '22 07:11

dylrei


Maybe you need someting like groupby of itertools

 from itertools import groupby

 data = MyObject.objects.all()

 [list(result) for key, result  in groupby(data, key=lambda item: item['type'])]
like image 22
Andres Avatar answered Nov 17 '22 06:11

Andres