6

With SQLAlchemy, it is possible to add a default value to every function. As I understand it, this may also be a callable (either without any arguments or with an optional ExecutionContext argument).

Now in a declarative scenario, I wonder if it is somehow possible to have a default function which is called with the object that is being stored. I.e. possibly like so:

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

Is something like this possible? Or do I have to somehow set up an before-insertion hook for this (how?)?

4

1 回答 1

4

before_insert is documented here:

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

examples here:

http://docs.sqlalchemy.org/en/rel_0_7/orm/events.html#mapper-events

i.e.

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"
于 2012-05-18T21:24:14.883 回答