Group queryset by attribute value

389 views Asked by At
class Customer(models.Model):
    ...

class Order(models.Model):
    customer = models.ForeignKey(Customer)

    def __unicode__(self):
        return "<Order customer={}".format(self.customer.pk)

Now imagine this

>>> Order.objects.all()
[<Order customer=1>, <Order customer=1>, <Order customer=2>]

Is it possible to get the result in a grouped manner? I can do it with loops but i'm looking for something like "group_by" if that exists? My backend is postgres

[[<Order customer=1>, <Order customer=1>], [<Order customer=2>]]

Order.objects.all().group_by('customer')

{AttributeError}'TreeQuerySet' object has no attribute 'group_by'

with loops:

orders = Order.objects.all()

data = {}
for order in orders:
    key = 'c_{}'.format(order.customer.pk)

    if key in data.keys():
         data[key].append(order)
    else:
         data[key] = [order]

>>> data.values()
[[<Order customer=1>, <Order customer=1>], [<Order customer=2>]]
0

There are 0 answers