我想在 SQLAlchemy 中使列“不可变”或“不可更新”。
现在我正在使用一个事件监听器,如果该列被更新,它会引发异常:
@event.listens_for(Person.email, 'set')
def receive_set_person_email(target, value, old_value, initiator):
if old_value != symbol('NEVER_SET') and old_value != symbol('NO_VALUE'):
raise AttributeError("Cannot change a Person's email")
但我想知道是否已经内置了类似的东西,或者我是否可以获得更漂亮、更通用的解决方案。
最佳答案
这是我的解决方案:
from sqlalchemy import event
from sqlalchemy.util.langhelpers import symbol
class NonUpdateableColumnError(AttributeError):
def __init__(self, cls, column, old_value, new_value, message=None):
self.cls = cls
self.column = column
self.old_value = old_value
self.new_value = new_value
if message is None:
self.message = 'Cannot update column {} on model {} from {} to {}: column is non-updateable.'.format(
column, cls, old_value, new_value)
def make_nonupdateable(col):
@event.listens_for(col, 'set')
def unupdateable_column_set_listener(target, value, old_value, initiator):
if old_value != symbol('NEVER_SET') and old_value != symbol('NO_VALUE') and old_value != value:
raise NonUpdateableColumnError(col.class_.__name__, col.name, old_value, value)
class Person(Base):
email = Column(String)
make_nonupdateable(Person.email)
关于python - 在 SQLAlchemy 中创建一列 "immutable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34953759/