下面是螞蟻的解決方案改寫的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)
哇你從哪兒弄來的?我從來沒有看到irc的螞蟻... – zzzeek
@zzzeek這只是螞蟻的彙編回答http://stackoverflow.com/questions/2317081/sqlalchemy-maximum-column-length/2317843#2317843和examples/custom_attributes/listen_for_events。 py –
謝謝,這正是我想要的。 – honzas