python - 一次写入只读字段

标签 python sqlalchemy

我们需要使用 SQLAlchemy/Elixir 实现一次写入(在对象创建时)只读字段。

一个快速而肮脏的解决方案:

class User(Entity):
    # some fields ...    
    _created    = Field(DateTime, default=datetime.utcnow)
    @property
    def created(self):
        return self._created

是否有更好的方法(例如,使用插入前触发器?)

最佳答案

可能有很多方法,但一种是使用 @validates :

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class A(Base):
    __tablename__ = 'a'

    id = Column(Integer, primary_key=True)

    readonly1 = Column(String)
    readonly2 = Column(String)


    @validates('readonly1', 'readonly2')
    def _write_once(self, key, value):
        existing = getattr(self, key)
        if existing is not None:
            raise ValueError("Field '%s' is write-once" % key)
        return value


a1 = A()
a1.readonly1 = 'foo'
assert a1.readonly1 == 'foo'

try:
    a1.readonly1 = 'bar'
    assert False
except ValueError, e:
    print e

e = create_engine("sqlite://")
Base.metadata.create_all(e)
s = Session(e)
s.add(A(readonly1='foo', readonly2='bar'))
s.commit()

a2 = s.query(A).first()

try:
    a2.readonly2 = 'bar2'
    assert False
except ValueError, e:
    print e

@validates 只是使用 attribute events 的简写您可以使用它来构建其他设置方式。

关于python - 一次写入只读字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16522845/

相关文章:

python - 防止 Flask jsonify 对数据进行排序

python - SQLAlchemy 版本控制关心类导入顺序

python - 从 SQLalchemy 中的自引用表创建树

python - 找不到 testing.postgresql 命令 : initdb inside docker

python - 在 flask 和其他应用程序之间共享 sqlalchemy 模型

python - 在python中读取yaml文件的行 block 并对其进行排序

python - 在 seaborn Pairgrid 中绘制下三角

python - Pandas 读取(Excel)文本列,并返回相似度

python - Python 探查器输出的 TreeMap 可视化 View ?

python - 如何使用 SQLAlchemy 创建一个新数据库?