SQLAlchemy声明中基于对象的默认值

时间:2012-05-15 11:02:06

标签: python sqlalchemy hook

使用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

这样的事情可能吗?或者我是否必须以某种方式为此设置插入前挂钩(如何?)?

1 个答案:

答案 0 :(得分:4)

此处记录了before_insert:

http://docs.sqlalchemy.org/en/rel_0_7/orm/events.html#sqlalchemy.orm.events.MapperEvents.before_insert

示例:

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"