Search code examples
pythonpeewee

Substring from select in Peewee ORM


I'm updating the codebase for my program from Peewee v2 to v3. In the code I perform a substring inside a select statement, which always worked in v2 but now no longer does. I've the following table

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),
    )

and my query is as followed:

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

This gives me the result:

None
None
None
None
None
None
None

However, if I leave the fn.substring out of my query the results are just fine like:

INH00001
INH00002
INH00004
INH00005
INH00006
INH00007
INH00008

The times I get "None" out of the first query do match the number of results from the second, so it's definitely selecting something. How can I make my first query work again so I get the results as expected? for example:

00001
00002
00004
00005
00006
00007
00008

Solution

  • I'm guessing something funky in the way you're accessing the attribute. Try specifying an alias explicitly:

    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)