Object-based default value in SQLAlchemy declarati

2020-07-12 03:37发布

问题:

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?)?

回答1:

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"