【问题标题】:Django Raw Query: Making Count query with group BY clauseDjango Raw Query:使用 group BY 子句进行计数查询
【发布时间】: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 好的提示-将其详细说明为答案。谢谢。

标签: python sql django


【解决方案1】:

一种可能的解决方案是直接使用connection.cursor() 并执行原始查询:

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()

【讨论】:

  • 啊。这很有意义。会尝试让你知道。我必须执行原始查询,所以我绝对可以使用游标。如果可行,将尝试然后接受这个作为答案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-28
  • 1970-01-01
  • 2016-05-09
  • 2021-04-05
  • 2022-11-02
  • 2023-04-04
  • 1970-01-01
相关资源
最近更新 更多