【发布时间】:2014-08-05 05:52:06
【问题描述】:
出于某种原因,我必须使用原始 SQL 查询,该查询将传递给 django 以使用 mymodel.objects.raw(query) 执行。但我看到主键需要始终传递。这就是阻止我进行一些查询的原因。
想象一个简单的查询,我在一个表上执行 count(*) 并对两列进行条件检查:
select count(*), column_value from tableX where column_label = 'Age' group by column_value having column_value > 30;
这在 pgsql 中可以正常工作并给出如下结果:
count | column_value
-------+----------------
1 | 38.00000
2 | 45.00000
1 | 35.00000
1 | 44.00000
注意第二行。那正是我想要的结果。但是使用 django 我必须传递主键,为此我必须更改查询,例如:
考虑 'id' 作为主键:
select count(*), id, column_value from tableX where column_label = 'Age' group by column_value, id having column_value > 30;
现在这会给我这样的东西:
count | id | column_value
-------+------+----------------
1 | 4041 | 45.00000
1 | 3876 | 38.00000
1 | 3821 | 45.00000
1 | 3931 | 35.00000
1 | 3986 | 44.00000
(5 rows)
即使在运行聚合命令之后我也能看到所有单独的行,这对我来说毫无用处。有没有其他方法可以仅使用 django 获得此处提到的第一个结果与 RAW 查询?破解主键的方法?
【问题讨论】:
-
您必须使用 mymodel.objects.raw 还是可以使用stackoverflow.com/a/2909886/827437 中解释的 django db 连接?
-
@vinod 好的提示-将其详细说明为答案。谢谢。