[英]Write-once read-only field
We need to implement a write-once (on object create) read-only field with SQLAlchemy/Elixir. 我们需要使用SQLAlchemy / Elixir实现一次写入(在对象创建时)只读字段。
A quick-and-dirty solution: 一个快速而肮脏的解决方案:
class User(Entity):
# some fields ...
_created = Field(DateTime, default=datetime.utcnow)
@property
def created(self):
return self._created
Is there a better approach (eg, using before-insert triggers?) 有没有更好的方法(例如,使用插入前触发器?)
Probably a lot of ways but one is to use a @validates : 可能有很多方法,但一个是使用@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 is just shorthand for using attribute events which you could use that to build out other ways of setting it up. @validates只是使用属性事件的简写,您可以使用它来构建其他设置方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.