django-orchestra-test/orchestra/models/queryset.py

22 lines
678 B
Python
Raw Normal View History

def group_by(qset, *fields, **kwargs):
2014-07-25 13:27:31 +00:00
""" group_by iterator with support for multiple nested fields """
ix = kwargs.get('ix', 0)
if ix is 0:
qset = qset.order_by(*fields)
group = []
2014-07-25 13:27:31 +00:00
first = True
for obj in qset:
current = getattr(obj, fields[ix])
2014-07-25 13:27:31 +00:00
if first or current == previous:
group.append(obj)
2014-07-25 13:27:31 +00:00
else:
if ix < len(fields)-1:
group = group_by(group, *fields, ix=ix+1)
yield previous, group
group = [obj]
2014-07-25 13:27:31 +00:00
previous = current
first = False
if ix < len(fields)-1:
group = group_by(group, *fields, ix=ix+1)
yield previous, group