On Apr 11, 2012, at 11:07 AM, Paddy Mullen wrote:
> MapperExtensions seem to be a deprecated interface to the same functionality
> that I am using with events
> http://docs.sqlalchemy.org/en/latest/orm/interfaces.html .
>
> I guess my fundamental problem is that I don't see a straightforward way to
> get a reference to a model instance in an "after_insert" or "after_update"
> event, after the changes have actually been committed to the database.
> Updates aren't as big a problem as inserts. For inserts, you can't easily
> enqueue the id of the model, because that ID hasn't been assigned yet.
The instance that was just inserted is passed to after_insert() as "target" (or
"instance" in the old system), and the primary key is absolutely there in the
after_insert() event, regardless of if the old or the new event system is in
use:
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)
@event.listens_for(A, "after_insert")
def assert_pk_is_there(mapper, conn, target):
print "PK!", target.id
assert target.id is not None
e = create_engine("sqlite://")
s = Session(e)
Base.metadata.create_all(e)
s.add(A())
s.commit()
classics-MacBook-Pro:sqlalchemy classic$ python test.py
PK! 1
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en.