2011-10-21 222 views
4

我使用SQLAlchemy最大列长度配方从我以前的问题(SQLAlchemy - maximum column length)。因为我升级到SQLAlchemy的0.7时,LengthValidator不能使用以下表达式安装:SQLAlchemy 0.7 - 最大列长度

inst.impl.extensions.insert(0,LengthValidator(col.type.length))

extension属性未在SQLAchemy 0.7中定义。有没有办法改变配方使用0.7?

感谢,honzas

回答

9

下面是蚂蚁的解决方案改写的SQLAlchemy的事件系统:

from sqlalchemy.ext.declarative import declarative_base 
from sqlalchemy.orm import ColumnProperty 
from sqlalchemy import event 

def check_string_length(cls, key, inst): 
    prop = inst.prop 
    # Only interested in simple columns, not relations 
    if isinstance(prop, ColumnProperty) and len(prop.columns) == 1: 
     col = prop.columns[0] 
     # if we have string column with a length, install a length validator 
     if isinstance(col.type, String) and col.type.length: 
      max_length = col.type.length 
      def set_(instance, value, oldvalue, initiator): 
       if len(value)>max_length: 
        raise ValueError("Length %d exceeds allowed %d" % \ 
              (len(value), max_length)) 
      event.listen(inst, 'set', set_) 

Base = declarative_base() 

event.listen(Base, 'attribute_instrument', check_string_length) 
+0

哇你从哪儿弄来的?我从来没有看到irc的蚂蚁... – zzzeek

+0

@zzzeek这只是蚂蚁的汇编回答http://stackoverflow.com/questions/2317081/sqlalchemy-maximum-column-length/2317843#2317843和examples/custom_attributes/listen_for_events。 py –

+0

谢谢,这正是我想要的。 – honzas

1

您可以使用sqlalchemy.orm.validates decorator

@validates('name') 
def validate_name(self, key, name): 
    assert len(name) <= 50 
    return name 
+0

这样,您必须为每个列安装验证程序,而原始解决方案作者参考时会处理所有字符串列(除内联合成材料以外的一些罕见情况),而无需额外工作。 –