2014-03-12 58 views
4

這工作動態定義字段:在peewee模型

class MyModel(peewee.Model): 
    my_field = peewee.IntegerField(null=False, default=0) 

    class Meta(object): 
     database = db 
     db_table = 'MyTable' 

這不起作用:

class MyModel(peewee.Model): 

    class Meta(object): 
     database = db 
     db_table = 'MyTable' 

setattr(MyModel, 'my_field', peewee.IntegerField(null=False, default=0)) 

我想這是由於peewee.Model做了一些魔法元類。事實上,我在模型的_meta.fields中看不到它。

什麼是動態定義字段的好方法?

回答

15

相反SETATTR的,叫add_to_class

my_field = peewee.IntegerField(null=False, default=0) 
my_field.add_to_class(MyModel, 'my_field_name') 

# Now this works: 
MyModel.my_field_name 
+0

顯然,這是現在:'Model._meta.add_field(FIELD_NAME,場)' – AidanGawronski

+0

https://github.com/coleifer/peewee/issues/1508 – AidanGawronski