Вопрос

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.

Это было полезно?

Решение

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>}

Другие советы

>>> x = [v for k,v in vars(Foo).items() if isinstance(v, peewee.FieldDescriptor)]
>>> for i in x:
...     print(i.att_name, i.field)
...
('bar', <peewee.CharField object at 0x022AC810>)
('baz', <peewee.CharField object at 0x022AC6B0>)
('id', <peewee.PrimaryKeyField object at 0x022B4CD0>)

This leverages the Python builtin vars generate a list of FieldDescriptor objects that class Foo holds. Note that we are operating on the Foo type object directly, obtaining this information from class variables.

Once we have all the fields, we can loop over them and examine the column name and type. Most likely, you'll want some kind of isinstance check on field to figure out type to use in your HTML. I imagine you'll want to filter out or ignore the PrimaryKeyField, but I think you can figure that out.

I would caution against doing this, though. It would probably be better to simply maintain the list of fields in your HTML. Yes, it's a little bit of a hassle, but automatically having new columns appear in the HTML page is not necessarily a good thing.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top