解密Peewee ORM Postgres查询错误

时间:2015-01-14 06:29:58

标签: orm flask peewee

我在Flask项目中使用Peewee。我有一个在SQLite中工作的ORM查询,但现在导致错误,因为我正在迁移到Postgres。我想知道是否有人可以帮助我诊断它:

stats = (
    Assignment.select(
        Type.name,
        fn.COUNT(Type.id).alias('total'),
        Assignment.select(
            fn.COUNT(Assignment.id)
        ).where(
            (Assignment.due_date < fn.Now()) & (StudentCourses.student == self) & (Assignment.type == Type.id)
        ).group_by(Assignment.type, StudentCourses.student).alias('completed')
    )
    .naive().join(Type)
    .join(StudentCourses, on=(StudentCourses.course == Assignment.course))
    .where(StudentCourses.student == self)
    .order_by(Type.id)
    .group_by(Type.name, StudentCourses.student)
)

以下是生成的SQL:

SELECT "t2"."name",
       COUNT("t2"."id") AS total,
  (SELECT COUNT("t4"."id")
   FROM "assignment" AS t4
   WHERE ((("t4"."due_date" < Now())
           AND ("t3"."student_id" = 2))
          AND ("t4"."type_id" = "t2"."id"))
   GROUP BY "t4"."type_id",
            "t3"."student_id") AS completed
FROM "assignment" AS t1
INNER JOIN "type" AS t2 ON ("t1"."type_id" = "t2"."id")
INNER JOIN "studentcourses" AS t3 ON ("t3"."course_id" = "t1"."course_id")
WHERE ("t3"."student_id" = 2)
GROUP BY "t2"."name",
         "t3"."student_id"
ORDER BY "t2"."id"

这是我得到的错误:

ProgrammingError: subquery uses ungrouped column "t2.id" from outer query
LINE 1: ...ND ("t3"."student_id" = 2)) AND ("t4"."type_id" = "t2"."id")...

我已经尝试将指定的列添加到group_by子句中,但我没有得到任何爱。有人对此有任何指导吗?会喜欢一双新鲜的眼睛。

1 个答案:

答案 0 :(得分:0)

您的子查询实际上正在加入外部查询的Type表,因此postgres表示您需要按COUNT子查询中的Type.id进行分组。