首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >peewee,如何查询指定的表?

问peewee,如何查询指定的表?
EN

Stack Overflow用户
提问于 2019-10-24 09:51:32
回答 1查看 54关注 0票数 0

我有peewee模型,它需要每天创建一个表,而不是我想要查询表MotorTable.query() Test20191021,但它今天总是查询表,我如何查询指定的表?

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-26 01:15:52

有几种方法可以解决这个问题。您可以在闭包中创建模型类,例如

代码语言:javascript
复制
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]

或者,您也可以每次都使用包装器显式设置表名:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58533061

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档