jett chen
jett chen

Reputation: 1173

peewee, how to query specified table?

i have peewee model, it need to create a table everyday, not i want to query table MotorTable.query() Test20191021 but it always query the table today, how can i query the specified table?

DB = SqliteDatabase('test.db')
def motor_db_table(model_cls):
    return 'Test{}'.format(time.strftime('%Y%m%d'))

class MotorTable(Model):
    date = DateTimeField()
    addr = CharField()
    status = CharField()

    class Meta:
        database = DB
        table_function = motor_db_table

Upvotes: 0

Views: 307

Answers (1)

coleifer
coleifer

Reputation: 26235

There are a couple ways you could go about this. You could create the model class in a closure, e.g.

model_cache = {}

def get_model_for_date(dt):
    tbl_name = 'Test' + dt.strftime('%Y%m%d')

    if tbl_name not in model_cache:
        class MotorTable(Model):
            date = DateTimeField()
            addr = TextField()
            status = CharField()
            class Meta:
                database = DB
                table_name = tbl_name
        if not MotorTable.table_exists():
            MotorTable.create_table()
        model_cache[tbl_name] = MotorTable

    return model_cache[tbl_name]

Alternatively, you could just explicitly set the table name each time using a wrapper:

def get_model(dt):
    table_name = 'Test' + dt.strftime('%Y%m%d')
    MotorTable._meta.set_table_name(table_name)
    if not MotorTable.table_exists():
        MotorTable.create_table()
    return MotorTable

Upvotes: 1

Related Questions