Peewee 查询 - 类型错误:“ModelCompoundSelectQuery”和“int”的实例之间不支持“>”

问题描述

peewee 3.7.0 中,执行以下代码时出现此错误

TypeError: '>' not supported between instances of 'ModelCompoundSelectQuery' and 'int'

def myMethod(lastItemDbId):
  # lastItemDbId is an int
  ...

  columnX = fn.Lower(People.name)

  lastItemColumnX = People.select(columnX).where(People.id == lastItemDbId)

  results = People.select(People.id).where(People.parent.is_null() & (columnX > lastItemColumnX | (columnX == lastItemColumnX & People.id > lastItemDbId))).order_by(columnX,People.id).limit(limit)

问题似乎出在 People.id > lastItemDbId 部分,但我不明白为什么。 删除 People.id > lastItemDbId 部分,错误消失了......但单独测试该部分也有效(见下文)

results = People.select(People.id).where(People.id > lastItemDbId).order_by(columnX,People.id).limit(limit)

如果您想知道,这是 peewee 模型定义:

class People(Model):
    name = CharField()
    parent = ForeignKeyField('self',backref='children',null=True,on_delete='CASCADE')

解决方法

来自 Peewee 文档:

请注意,实际比较用括号括起来。 Python 的运算符优先级要求将比较括在括号中。

即使显然是多余的,解决方案也是将在“&”和“|”等按位运算符左侧和右侧找到的每个逻辑部分都用括号括起来。

所以解决方案是:

results = People.select(People.id).where((People.parent.is_null()) & ((columnX > lastItemColumnX) | ((columnX == lastItemColumnX) & (People.id > lastItemDbId)))).order_by(columnX,People.id).limit(limit)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...