the whole behavior is done using event handlers which is public API. so you could set up the attributeevents.append() [1] and attributeevents.set() [2] event handlers to add the local side to the session:
from sqlalchemy import Column
from sqlalchemy import create_engine
from sqlalchemy import event
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import object_session
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session
from sqlalchemy.orm import configure_mappers
Base = declarative_base()
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
data = Column(String)
bs = relationship("B", backref="a")
class B(Base):
__tablename__ = "b"
id = Column(Integer, primary_key=True)
a_id = Column(ForeignKey("
a.id"))
data = Column(String)
configure_mappers()
@event.listens_for(B.a, "set")
def set_(target, newvalue, oldvalue, initiator):
sess = object_session(newvalue)
if target not in sess:
sess.add(target)
e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)
s = Session(e)
a1 = A()
s.add(a1)
s.commit()
b1 = B(a=a1)
assert b1 in s.new
For a given chain of methods that are working in the same transaction I would have a Session that's passed around to all of them, likely via some contextual object, so that they can all ensure the object is added to the persistence context as needed. calling a sessionmaker inside of each method implies you're building a new session/transaction inside of each method which means each method would need to commit its own transaction, did you mean the scoped_session()? scoped_session is an option as well if you are already using that, though I favor an explicit session/context being passed around as this allows functions and methods to explicitly state that they need to take place within this particular kind of context.
--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
---
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.