Python Django原始查询:使用group BY子句进行计数查询
出于某种原因,我必须使用原始SQL查询,该查询将传递给django,以使用mymodel.objects.raw(查询)执行。但是我发现主键需要总是被传递。这就是阻止我提出一些疑问的原因 想象一下一个简单的查询,其中我对一个表进行计数(*),并对两列进行条件检查:Python Django原始查询:使用group BY子句进行计数查询,python,sql,django,Python,Sql,Django,出于某种原因,我必须使用原始SQL查询,该查询将传递给django,以使用mymodel.objects.raw(查询)执行。但是我发现主键需要总是被传递。这就是阻止我提出一些疑问的原因 想象一下一个简单的查询,其中我对一个表进行计数(*),并对两列进行条件检查: select count(*), column_value from tableX where column_label = 'Age' group by column_value having column_value > 3
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通过原始查询获得这里提到的第一个结果?绕过主键的某种方法?一种可能的解决方案是直接使用并执行原始查询:
from django.db import connection
cursor = connection.cursor()
cursor.execute("""select
count(*), column_value
from
tableX
where
column_label = 'Age'
group by
column_value
having
column_value > 30""")
result = cursor.fetchall()
您是否必须使用mymodel.objects.raw,或者是否可以使用django db连接,如@vinod good tip所述-在答案中详细说明。谢谢,啊。这很有道理。我会尽力让你知道的。我必须执行原始查询,这样我肯定也可以使用游标。如果有效,将尝试并接受此答案:)