由于某些原因,我必须使用原始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查询获得此处提到的第一个结果?是否有一些绕过主键的方法?