Search code examples
pythonmysqlpeewee

How create fields(columns in db) from a dictionary(iterating) with peewee


I'm new to peewee and python . And i'm trying to create a mysql table with keys from a dictionary as field names. I've tried the code below but it makes only one field in database = 'key'. Looks like peewees framework doesn't see variables. I think it has to be another elegant way to do it, but i'm confused.

from peewee import *
db = MySQLDatabase('exop', user='root',passwd='12345')
dict = {'a' : '1', 'b' : '2',  'c': '3'}
class Dict2db(Model):
    for key in dict:
        key = CharField()

    class Meta:
        database = db
db.connect()
db.create_table(Dict2db)

Solution

  • You probably want to use type:

    attrs = {field: CharField() for field in dict}
    Dict2db = type('Dict2db', (Model,), attrs)