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>]]
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>]}
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'])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With