事情很簡單,一旦你掌握了它。 下面是一個使用事件
import uuid
from sqlalchemy.event import listen
from mypackage.models import Base
def generate_license(mapper, connect, target):
target.generate_license()
class User(Base):
__tablename__ = "users"
id = Column(String(36))
license = Column(String(256))
def generate_license(self):
if not self.license:
self.license = str(uuid.uuid4())
return self.license
listen(User, 'before_insert', generate_license)
或者,你可以使用裝飾一個簡單的例子:
from sqlalchemy.event import listens_for
…
class User(Base):
…
@listens_for(User, 'before_insert')
def generate_license(mapper, connect, self):
…
請查看更新的答案 – amigcamel