Dynamically define name of class in peewee model

三世轮回 提交于 2019-12-13 23:51:40

问题


I'm trying to assign a class name dynamically using a string.

Much like this...

classname='cats'

class classname(peewee.Model):

Peewee doesn't seem to think I should be able to do this and I'm having a lot of trouble finding a way to define the class name dynamically.

Help!


回答1:


If you need to control the table name, you can do:

 class MyModel(Model):
     whatever = CharField()

     class Meta:
         db_table = 'my_table_name'



回答2:


I have a same problem with you,and find a solution at last. Maybe it's not a good idea to Dynamically define name of class in peewee model.

class Person(Model):
    name = CharField()
    birthday = DateField()
    is_relative = BooleanField()

    class Meta:
        database = db
        db_table = "Hello"

>>> Person.__dict__
mappingproxy({'DoesNotExist': <class 'peewee.PersonDoesNotExist'>,       'is_relative': <peewee.FieldDescriptor object at 0x000000000470BEF0>, 'name': <peewee.FieldDescriptor object at 0x000000000470BF60>, '_meta': <peewee.ModelOptions object at 0x000000000470BE48>, 'birthday': <peewee.FieldDescriptor object at 0x000000000470BF98>, 'id': <peewee.FieldDescriptor object at 0x000000000470BEB8>, '__module__': 'data', '_data': None, '__doc__': None})

You could see clearly what meta class means in the __dict__,and you can change it in this way:

 setattr(Person._meta, "db_table", "another")

 db.connect()
 db.create_table(Person)

I'm not a native English speaker and a newbie in programming,but I hope the solution is helpful for you.




回答3:


Using the "exec" function would be easiest way of doing this:

CLASS_TEMPLATE = """\
class %s(peeww.Model):
    pass
"""

classname = "cats"
exec(CLASS_TEMPLATE % classname)

c = cats()   # works !

Explanation:

I've created a string named CLASS_TEMPLATE which contains Python code creating a class. I use a format specifier %s as a class name, so it can be replaced.

Doing this:

CLASS_TEMPLATE % "cats"

replaces the format specifier %s and creates a string that contains the code to create a class named "cats".

If you ask Python to execute this code, your class gets defined:

exec(CLASS_TEMPLATE % "cats")

You can see that it exists in your namespace:

>>> globals()
{..., 'cats': <class __main__.cats at 0x1007b9b48>, ...}

... and that it is a class:

>>> type(cats)
<type 'classobj'>

And you can start using this newly defined class to instantiate objects:

c = cats()


来源:https://stackoverflow.com/questions/25709353/dynamically-define-name-of-class-in-peewee-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!