2014-09-08 10:03:42 +00:00
|
|
|
from .utils import get_field_value
|
|
|
|
|
|
|
|
|
2014-07-28 17:28:00 +00:00
|
|
|
def group_by(qset, *fields, **kwargs):
|
2014-07-25 13:27:31 +00:00
|
|
|
""" group_by iterator with support for multiple nested fields """
|
2014-07-28 17:28:00 +00:00
|
|
|
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
|
2014-07-28 17:28:00 +00:00
|
|
|
for obj in qset:
|
2014-09-08 10:03:42 +00:00
|
|
|
try:
|
|
|
|
current = get_field_value(obj, fields[ix])
|
|
|
|
except AttributeError:
|
|
|
|
# Intermediary relation does not exists
|
|
|
|
current = None
|
2014-07-25 13:27:31 +00:00
|
|
|
if first or current == previous:
|
2014-07-28 17:28:00 +00:00
|
|
|
group.append(obj)
|
2014-07-25 13:27:31 +00:00
|
|
|
else:
|
2014-07-28 17:28:00 +00:00
|
|
|
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
|
2014-07-28 17:28:00 +00:00
|
|
|
if ix < len(fields)-1:
|
|
|
|
group = group_by(group, *fields, ix=ix+1)
|
|
|
|
yield previous, group
|