I am pretty sure this is not a duplicate. I know we can 'dynamically' set the table name using this:
class DBmodel(Model)
class Meta:
database = db
table_name = "foobar"
But what if I want to change table_name
every time DBmodel
is instanced?
For example consider this working snippet:
#!/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()
So I get:
$ 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));
But I want to have two tables like this:
$ 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));
Of course, I could duplicate my DBmodel
and change table_name
every time, but this seems ugly. Is there a better solution?
You can always declare classes dynamically using the builtin type
:
attrs = {
'foo': TextField(),
'bar': TextField(),
}
MyModel = type('MyModel', (BaseModel,), attrs)
Why does your "Data" have to be a class? Presumably all you need is a function that accepts a key to the config dict and you would return a new class object. You might want to think about that.
I'll also point out that doing this is a bad idea.
# 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()
DBmodel._meta.set_table_name(<table_name>)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.