Peewee:实例化模型时动态设置table_name

时间:2019-01-05 12:25:39

标签: python orm peewee

我很确定这不是重复的。我知道我们可以使用以下方法“动态”设置表名:

class DBmodel(Model)
    class Meta:
        database = db
        table_name = "foobar"

但是,如果我想在每次实例化table_name时更改DBmodel怎么办?

例如,考虑以下工作片段:

#!/usr/bin/env python3
# coding: utf-8

from peewee import *

conf = {
    "foo": {
        "foo1": "CharField(null=True)",
        "foo2": "CharField(null=True)"
    },
    "bar": {
        "bar1": "CharField(null=True)",
        "bar2": "CharField(null=True)"
    }
}

db = SqliteDatabase("foobar.db")


class DBmodel(Model):
    class Meta:
        database = db
        table_name = "foobar"


class Data:
    def __init__(self, conf):
        self.conf = conf
        self.DBmodel = DBmodel()
        for entry in self.conf:
            # I have to use eval because my conf is actually coming from parsed json, where I can only have text field
            self.DBmodel._meta.add_field(entry, eval(self.conf[entry]))


if __name__ == "__main__":
    dataFoo = Data(conf["foo"])
    dataBar = Data(conf["bar"])
    dataFoo.DBmodel.create_table()
    dataBar.DBmodel.create_table()

所以我得到了

$ sqlite3 foobar.db
SQLite version 3.22.0 2018-01-22 18:45:57
sqlite> .schema foobar
CREATE TABLE IF NOT EXISTS "foobar" ("id" INTEGER NOT NULL PRIMARY KEY, "foo1" VARCHAR(255), "foo2" VARCHAR(255), "bar1" VARCHAR(255), "bar2" VARCHAR(255));

但是我想有两个这样的表:

$ sqlite3 foobar.db
SQLite version 3.22.0 2018-01-22 18:45:57
sqlite> .schema foo
CREATE TABLE IF NOT EXISTS "foo" ("id" INTEGER NOT NULL PRIMARY KEY, "foo1" VARCHAR(255), "foo2" VARCHAR(255));
sqlite> .schema bar
CREATE TABLE IF NOT EXISTS "bar" ("id" INTEGER NOT NULL PRIMARY KEY, "bar1" VARCHAR(255), "bar2" VARCHAR(255));

当然,我可以复制我的DBmodel并每次更改table_name,但这看起来很丑。有更好的解决方案吗?

2 个答案:

答案 0 :(得分:0)

您始终可以使用内置的type动态声明类:

attrs = {
    'foo': TextField(),
    'bar': TextField(),
}
MyModel = type('MyModel', (BaseModel,), attrs)

为什么您的“数据”必须是一类?大概您所需要的只是一个接受config dict键的函数,您将返回一个新的类对象。您可能需要考虑一下。

我还要指出,这样做不是一个好主意。

答案 1 :(得分:0)

 # coding: utf-8
 from peewee import *
 db = SqliteDatabase("foobar.db")
 def get_table_name(model_class):
     return model_class.__name__

 def class_generator(class_name):
     value_dict = {}
     for i in range(2):
         value_dict['{}{}'.format(class_name, i+1)] = CharField(null=True)
     value_dict['Meta'] = type('Meta', (object, ), {'database': db, 'table_function': get_table_name})
     return type(class_name, (Model, ), value_dict)

 if __name__ == "__main__":
     dataFoo = class_generator("foo")
     dataBar = class_generator("bar")
     dataFoo.create_table()
     dataBar.create_table()