class Customer(models.Model):
...
class Order(models.Model):
customer = models.ForeignKey(Customer)
def __unicode__(self):
return "<Order customer={}".format(self.customer.pk)
现在想象一下
>>> Order.objects.all()
[<Order customer=1>, <Order customer=1>, <Order customer=2>]
是否可以按分组方式获得结果?我可以用循环来做,但我正在寻找像&#34; group_by&#34;如果存在?我的后端是postgres
[[<Order customer=1>, <Order customer=1>], [<Order customer=2>]]
Order.objects.all().group_by('customer')
{AttributeError的}&#39; TreeQuerySet&#39;对象没有属性&#39; group_by&#39;
有循环:
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>]]