How to automatically add a SQLAlchemy object to a session?

I have a SQLAlchemy table class created using the Declarative method:

mysqlengine = create_engine(dsn)
session = scoped_session(sessionmaker(bind=mysqlengine))
Base = declarative_base()
Base.metadata.bind = mysqlengine

class MyTable(Base):
  __table_args__ = {'autoload' : True}

Now that this table is used in the code, I would not have to use the session.add method to add each new record to the active session, but instead:

row = MyTable(1, 2, 3)
session.add(row)
session.commit()

I would like to:

row = MyTable(1, 2, 3)
session.commit()

Now I know about this question: Can I add an object to an SQLAlchemy session without explicit session.add ()?

And I understand that you can force this behavior to do the following:

class MyTable(Base):
  def __init__(self, *args, **kw):
    super(MyTable, self).__init__(*args, **kw)
    session.add(self)

However, I do not want to inflate my code containing 30 tables with this method. I also know that Elixir ( http://elixir.ematia.de/trac/wiki ) does this so that it should be possible in a way.

+5
source share
1 answer

Super simple. Use the event:

from sqlalchemy import event, Integer, Column, String
from sqlalchemy.orm import scoped_session, sessionmaker, mapper
from sqlalchemy.ext.declarative import declarative_base

Session = scoped_session(sessionmaker())

@event.listens_for(mapper, 'init')
def auto_add(target, args, kwargs):
    Session.add(target)

Base = declarative_base()

class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)
    data = Column(String)

a1 = A(data="foo")
assert a1 in Session()
+15
source

All Articles