且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有Postgresql的Django,列必须出现在GROUP BY子句中或在聚合函数中使用

更新时间:2023-09-17 08:10:22

这是Django> = 1.8和Django< 2.0。它已在Django 2.0中修复。我遇到了同样的问题,并在django-users邮件列表中提出来。

This is a known bug in Django >= 1.8 and Django < 2.0. It has been fixed in Django 2.0. I had the same problem and brought it up in the django-users mailing list.

发生的事情是Django执行了一些优化,尤其是基于PostgreSQL的优化。在PostgreSQL中,您只需要在GROUP BY子句中使用pk列,但这仅用于表。 (如果这样做,查询将更快地运行。)在PostgreSQL的视图中不能拥有PK,这就是为什么这对我们来说是个问题,因为我们在后端使用了非托管模型和视图。

What happened is that Django performed some optimizations, especially based on PostgreSQL. In PostgreSQL, you only need to use the pk columns in the GROUP BY clause, but that is only for tables. (The query runs more quickly if you do that.) You cannot have a PK in a view in PostgreSQL, which is why it is a problem for us since we are using un-managed models coupled with views in the backend.

参考:

  • https://github.com/django/django/commit/daf2bd3efe53cbfc1c9fd00222b8315708023792
  • https://groups.google.com/forum/#!topic/django-developers/lx3ZSq-W9X4
  • https://groups.google.com/d/msg/django-developers/lx3ZSq-W9X4/yh4I2CsoBwAJ
  • https://code.djangoproject.com/ticket/28107