Can I add an object to a SQLAlchemy session without explicit session.add ()?

I have several classes that map to tables with SQLAlchemy (not declaratively if that matters). Since I want the application to be tested per unit, all SQLAlchemy session interactions are isolated in the same class. Using the application looks something like this:

m = Model("mysql://localhost/mydb")
s1 = Service("somename")
m.session.add(s1)
s1 is m.get_service("somename") # True

This is actually more optimized, but work with me here.

Is it possible to skip the session.add () step? In other words, if I create an instance of the mapped class, is it possible that this will be automatically added to the active SQLAlchemy session (if any)?

+3
source share
2 answers

, . " ", .add . , db/session. :

a1 = Author(name='Pynchon') # out of session
session.add(a1) # in session
b1 = Book(name='Gravity`s Rainbow') # out of session
b1.author = a1 #in session
a2 = session.query(Author).filter(name='Eco').one() # in session
b2 = Book(name='Baudolino') # out of session
b2.author = a2 # in session

Of course, you need to indicate in advance the relationship "author" between the cartographers.

+2
source

All Articles