我正在使用,sqlalchemy但发现难以搜索的文档.
我有这两列:
verified = Column(Boolean, default=False)
verified_at = Column(DateTime, nullable=True)
Run Code Online (Sandbox Code Playgroud)
我想创建一个像这样的函数:
if self.verified and not oldobj.verified:
self.verified_at = datetime.datetime.utcnow
if not self.verified and oldobj.verified:
self.verified_at = None
Run Code Online (Sandbox Code Playgroud)
我不知道在哪里放这样的代码.我可以把它放在应用程序中,但更喜欢该model对象处理这个逻辑.
我认为你所寻找的是一个混合财产.
from sqlalchemy.ext.hybrid import hybrid_property
class VerifiedAsset(Base):
id = Column(Integer, primary_key=True)
verified_at = Column('verified_at', String(24))
@hybrid_property
def verification(self):
return self.verified_at;
@verification.setter
def verification(self, value):
if value and not self.verification:
self.verified_at = datetime.datetime.utcnow
if not value and self.verification:
self.verified_at = None
# Presumably you want to handle your other cases here
Run Code Online (Sandbox Code Playgroud)
您希望verified_at根据某些传入的新值以特定方式更新您的值.使用属性来包装基础值,并且仅在适当时更新,并且仅对您在db中实际持久存储的内容进行更新.
小智 3
您可以使用 sqlalchemy 的事件注册来放置如下代码: http: //docs.sqlalchemy.org/en/latest/core/event.html。基本上,您可以订阅 Core 和 ORM 中发生的某些事件。我认为这是一种管理您想要实现的目标的干净方法。
您可以使用listen_for()装饰器,以便在这些列发生更改时进行挂钩。