【发布时间】:2010-04-01 08:11:47
【问题描述】:
我正在尝试构建一个查询来获取“每个用户购买的商品的平均、最大和最小数量”。
数据源就是这个简单的销售记录表:
class SalesRecord(models.Model):
id = models.IntegerField(primary_key=True)
user_id = models.IntegerField()
product_code = models.CharField()
price = models.IntegerField()
created_at = models.DateTimeField()
用户购买的每件商品都会在此表中插入一条新记录。
[注意]:user_id 不是同一数据库中表的外键,因为此后端系统不管理用户信息。该值由产品的前端部分提供。
这是我构建查询的尝试:
q = SalesRecord.objects.all()
q = q.values('user_id').annotate( # group by user and count the # of records
count=Count('id'), # (= # of items)
).order_by()
result = q.aggregate(Max('count'), Min('count'), Avg('count'))
当我尝试执行代码时,在最后一行出现ProgrammingError:
(1064, "您的 SQL 中有错误 句法;检查手册 对应你的 MySQL 服务器 使用正确语法的版本 靠近'从(选择
sales_records.user_idASuser_id, COUNT(sales_records.`' 在第 1 行")
Django 的错误画面显示 SQL 是
SELECT FROM
(SELECT
`sales_records`.`user_id` AS `user_id`,
COUNT(`sales_records`.`id`) AS `count`
FROM `sales_records`
WHERE (`sales_records`.`created_at` >= %s AND `sales_records`.`created_at` <= %s )
GROUP BY `sales_records`.`user_id` ORDER BY NULL) subquery
它没有选择任何东西!有人可以告诉我正确的方法吗?
破解 Django
我发现清除django.db.models.sql.query.BaseQuery.get_aggregation() 中选定字段的缓存似乎可以解决问题。虽然我不确定这是修复还是解决方法。
@@ -327,10 +327,13 @@
# Remove any aggregates marked for reduction from the subquery
# and move them to the outer AggregateQuery.
+ self._aggregate_select_cache = None
+ self.aggregate_select_mask = None
for alias, aggregate in self.aggregate_select.items():
if aggregate.is_summary:
query.aggregate_select[alias] = aggregate
- del obj.aggregate_select[alias]
+ if alias in obj.aggregate_select:
+ del obj.aggregate_select[alias]
...产生结果:
{'count__max': 267, 'count__avg': 26.2563, 'count__min': 1}
【问题讨论】:
标签: django django-models django-aggregation