Passiday
Passiday

Reputation: 8105

SQLAlchemy: how to pass extra parameters when instantiating new object

I have defined a table, using SQLAlchemy and mapped it to a class:

meta = MetaData(engine)
item_table = Table(
    'Item', meta,
    Column('id', Integer, primary_key=True, nullable=False),
    Column('name', String(40), nullable=False)
)

class Item(object):
    def init(self, created_by):
        self.created_by = created_by
    def __repr__(self):
        return '<Item %r created by %r>' % (self.name, self.created_by)

mapper(Item, item_table)

As you see, the Item has a created_by field that does not come from the database. Currently I survive using item.init("created_by") method, what is called immediately after creating an instance of item. I find this kind of ugly, perhaps there is a better way to handle this.

Upvotes: 2

Views: 1789

Answers (1)

van
van

Reputation: 77082

You can subscribe to the load event and execute your logic there:

class DB(object):
    def __init__(self):
        self._register_event()

    def _get_created_by(self):
        return datetime.datetime.now()

    def _register_event(self):
        @event.listens_for(Item, 'load')
        def receive_load(target, context):
            target.created_by = self._get_created_by()

    def test_select(self):
        items = session.query(Item).all()
        for item in items:
            print(item)

db = DB()
db.test_select()

Upvotes: 1

Related Questions