我有包含字段customer_id和其他一些字段的表invoices。我需要选择购买计数,由每个用户采取。在SQL中,它应该如下所示:
SELECT username, COUNT('customer_id') FROM `invoices`
LEFT JOIN `auth_user` ON `auth_user`.id = `invoices`.customer_id
GROUP BY `customer_id`, username在Django中,我尝试:
Invoice.objects.annotate(buy_count=Count('customer')).all()但此代码按invoices.id而不是invoices.customer_id进行分组,并返回错误的结果。
发布于 2012-02-26 22:47:03
我认为你应该把它扭转过来,比如:
Customer.objects.annotate(buy_count=Count('invoice')).all()在那里,您将获得一个客户列表,其中包含他们的发票数量。
https://stackoverflow.com/questions/9454012
复制相似问题