使用sqlAlchemy,可以为每个函数添加默认值.据我所知,这也可能是一个可调用的(没有任何参数或可选的ExecutionContext参数).
现在在一个声明性场景中,我想知道是否有可能有一个默认函数,该函数是使用正在存储的对象调用的.即可能是这样的:
Base = sqlalchemy.ext.declarative.declarative_base()
class BaseEntity(Base):
value = Column('value',String(40),default=BaseEntity.gen_default)
def gen_default(self):
# do something with self,for example
# generate a default value using some other data
# attached to the object
return self.default_value
这样的事情可能吗?或者我必须以某种方式为此设置一个插入前挂钩(如何?)?
最佳答案
before_insert在这里记录:
原文链接:https://www.f2er.com/python/439293.html这里的例子:
http://docs.sqlalchemy.org/en/rel_0_7/orm/events.html#mapper-events
即
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import event
Base= declarative_base()
class A(Base):
__tablename__ = "a"
id = Column(Integer,primary_key=True)
data = Column(String)
otherdata = Column(String)
@event.listens_for(A,"before_insert")
def gen_default(mapper,connection,instance):
instance.data = "Some default %s" % instance.otherdata
e = create_engine("sqlite://")
Base.Metadata.create_all(e)
a = A(otherdata="some other data")
s = Session(e)
s.add(a)
s.commit()
assert a.data == "Some default some other data"