【问题标题】:How to replace group_by in sqlalchemy query so that postgresql database does not throw an error如何在sqlalchemy查询中替换group_by,使postgresql数据库不报错
【发布时间】:2020-07-24 16:49:36
【问题描述】:

在我尝试将我的应用程序部署到 heroku 之前,我的烧瓶文件中有一个有效的查询。它工作的原因是我在本地使用 sqlite3 数据库,但必须在生产模式下使用 postgresql 数据库。

我遇到但无法解决的问题是以下 sqlalchemy 查询:

companies = StaffMember.query.filter_by(user_id=current_user.id).group_by(StaffMember.company).all()

当我在 postgresql 中运行时,我收到以下错误:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.GroupingError) 列“staffMembers.id”必须出现在 GROUP BY 子句中或用于聚合函数中

根据我的发现,问题是 group_by 在 postgresql 中的工作方式不同,我应该尝试使用关键字“distinct”。但我真的不知道如何正确使用 distinct 来生成在 sqlalchemy 中独一无二的公司列表。

我尝试过类似的方法:

companies = StaffMember.query.filter_by(user_id=current_user.id).distinct(StaffMember.company).all()

或:

companies = StaffMember.query.filter_by(user_id=current_user.id).filter_by(StaffMember.company).distinct()

我认为我没有正确创建查询。

我曾尝试阅读这些文档,但以我目前的编码水平,我无法真正理解它们。

【问题讨论】:

  • 我认为您需要在第一个查询中在 group_by 中添加 staffMembers.id

标签: python postgresql flask sqlalchemy


【解决方案1】:

如果您想在表格中获取所有不同公司的列表,您可以这样做:

companies = StaffMember.query.with_entities(
     StaffMember.company
).filter_by(
    user_id=current_user.id
).distinct()

也可以:

companies = session.query(
     StaffMember.company
).filter_by(
    user_id=current_user.id
).distinct()

在这种情况下,使用 group by 或 distinct 将产生相同的结果。如果要使用分组依据,所有未聚合的选定列必须在.group_by()内。

【讨论】:

  • 谢谢。第一个查询完美运行。感谢您的回答。
猜你喜欢
  • 1970-01-01
  • 2021-11-03
  • 2016-04-23
  • 2023-03-13
  • 1970-01-01
  • 2011-10-08
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多