我有peewee模型,它需要每天创建一个表,不是我想查询表MotorTable.query()
Test20191021
但它今天总是查询表,我如何查询指定的表?
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
有几种方法可以解决这个问题。您可以在闭包中创建模型类,例如
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]
或者,您可以每次使用包装器显式设置表名:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句