Peewee ORM中select的子字符串

时间:2019-10-08 11:30:59

标签: python peewee

我正在将我的程序的代码库从Peewee v2更新到v3。 在代码中,我在select语句中执行了一个子字符串,该语句始终在v2中起作用,但现在不再起作用。 我有下表

class Project(BaseModel):
project_id = CharField(column_name='projectID', primary_key=True)
name = CharField()
relative_path = CharField()
product_id = ForeignKeyField(column_name='productID', model=Product, field='product_id')

class Meta:
    table_name = 'project'
    indexes = (
        (('name', 'product_id'), True),
    )

我的查询如下:

project_prefix = "INH"

query = internal_projects = Project.select(fn.substring(Project.project_id, len(project_prefix) + 1))\
.where(Project.project_id.startswith(project_prefix))

for q in query:
    print q

这给了我结果:

None
None
None
None
None
None
None

但是,如果我将fn.substring留在查询之外,则结果就像:

INH00001
INH00002
INH00004
INH00005
INH00006
INH00007
INH00008

我从第一个查询中得到“无”的时间与第二个查询中的结果的数量相匹配,因此肯定是在选择一些东西。如何使我的第一个查询再次起作用,以便按预期方式获得结果?例如:

00001
00002
00004
00005
00006
00007
00008

1 个答案:

答案 0 :(得分:0)

我猜想您访问属性的方式有些时髦。尝试明确指定别名:

pid = fn.substring(Project.project_id, len(prefix + 1))
query = (Project
         .select(pid.alias('pid'))
         .where(Project.project_id.startswith(prefix)))

for project in query:
    print(project.pid)