How to create fields (columns in db) from dictionary (iteration) with peewee

I am new to peewee and python. And I am trying to create a mysql table with keys from dictionary as field names. I've tried the code below, but it only makes one field in the database = 'key'. It looks like the peewees framework doesn't see the variables. I think this should 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)

      

+3


source to share


1 answer


You probably want to use type

:



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

      

+1


source







All Articles