2011-07-21 21 views
3

让我们举个例子,一个用户Schema在站点管理员设置要求的电话号码数量:formencode架构字段添加动态

class MySchema(Schema): 
    name = validators.String(not_empty=True) 
    phone_1 = validators.PhoneNumber(not_empty=True) 
    phone_2 = validators.PhoneNumber(not_empty=True) 
    phone_3 = validators.PhoneNumber(not_empty=True) 
    ... 

不知怎的,我以为我可以简单地做:

class MySchema(Schema): 
    name = validators.String(not_empty=True) 
    def __init__(self, *args, **kwargs): 
     requested_phone_numbers = Session.query(...).scalar() 
     for n in xrange(requested_phone_numbers): 
      key = 'phone_{0}'.format(n) 
      kwargs[key] = validators.PhoneNumber(not_empty=True) 
     Schema.__init__(self, *args, **kwargs) 

因为我在FormEncode docs中读到:

验证器使用实例变量来存储他们的customiza信息 信息。您可以使用子类化或正常实例化来设置这些。

Schema被称为文档作为复合验证,是FancyValidator子类,所以我猜它是正确的。

但这不起作用:只需添加phone_n就会被忽略,只需要name

更新:

此外,我都尝试重写__new____classinit__没有成功前问...

回答

5

我有同样的问题,我在这里找到了解决方案: http://markmail.org/message/m5ckyaml36eg2w3m

所有的事情就是使用你的模式的add_field方法init方法

class MySchema(Schema): 
    name = validators.String(not_empty=True) 

    def __init__(self, *args, **kwargs): 
     requested_phone_numbers = Session.query(...).scalar() 
     for n in xrange(requested_phone_numbers): 
      key = 'phone_{0}'.format(n) 
      self.add_field(key, validators.PhoneNumber(not_empty=True)) 

我不认为有必要调用父初始化

+0

是的!谢谢!经过一个多小时寻找解决方案后,这才解决了我的问题。 – Brodan