Skip to content Skip to sidebar Skip to footer

Dynamically Define Name Of Class In Peewee Model

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 d

Solution 1:

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

classMyModel(Model):
     whatever = CharField()

     classMeta:
         db_table = 'my_table_name'

Solution 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.

classPerson(Model):
    name = CharField()
    birthday = DateField()
    is_relative = BooleanField()

    classMeta:
        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.

Solution 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__.catsat0x1007b9b48>, ...}

... and that it is a class:

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

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

c = cats()

Post a Comment for "Dynamically Define Name Of Class In Peewee Model"