Search code examples
pythonpeewee

Peewee - Determining meta data about Model at run time


class Foo(Model):
    bar = CharField()
    baz = CharField()
    class Meta:
        database = db

<body>
    Create a new Foo:
    <input type="text" name="bar" />
    <input type="text" name="baz" />
</body>

Instead of hard coding the input fields in the html, I would like to be able to determine at run time the names, data types, and other meta data about the fields in a model, and pass them to the html template to loop over.


Solution

  • You can do Model._meta.fields:

    In [1]: from peewee import *
    
    In [2]: class User(Model):
       ...:     username = CharField()
       ...:     
    
    In [3]: User._meta.fields
    Out[3]: 
    {'id': <peewee.PrimaryKeyField at 0x2eba290>,
     'username': <peewee.CharField at 0x2eb4e10>}