peewee,如何查询指定的table?
peewee, how to query specified table?
我有 peewee 模型,它需要每天创建一个 table,不是我想查询 table MotorTable.query()
Test20191021
但它总是查询 table今天如何查询指定的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
您可以通过多种方式解决此问题。您可以在闭包中创建模型 class,例如
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]
或者,您可以在每次使用包装器时显式设置 table 名称:
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
我有 peewee 模型,它需要每天创建一个 table,不是我想查询 table MotorTable.query()
Test20191021
但它总是查询 table今天如何查询指定的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
您可以通过多种方式解决此问题。您可以在闭包中创建模型 class,例如
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]
或者,您可以在每次使用包装器时显式设置 table 名称:
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