Search code examples
pythonpeewee

peewee not using dynamic table name in select statement


Why does the select statement here have t1 instead of MyDynamicTable?

from peewee import *

database = SqliteDatabase(None)


class Base(Model):
    class Meta:
        database = database


class MyTable(Base):
    FieldA = TextField()
    FieldB = TextField()


mytable = type('MyDynamicTable', (MyTable,), {})

database.init('test.db')

mytable.select()

Leads to:

>>> mytable.select()
<class 'peewee.MyDynamicTable'> SELECT "t1"."id", "t1"."FieldA", "t1"."FieldB" FROM "mydynamictable" AS t1 []

But the name is correct:

>>> mytable
<class 'peewee.MyDynamicTable'>
>>> mytable._meta.db_table
'mydynamictable'

Solution

  • Peewee has aliased your table name. If you read the full query:

    SELECT "t1"."id", "t1"."FieldA", "t1"."FieldB"
    FROM "mydynamictable" AS t1
    

    The "mydynamictable" AS t1 part aliases the table name to "t1", to make the query more compact. This is especially important when you have joins and need to disambiguate columns with the same name.