Hi All,
I've been experimenting with the new event system in 7.1, and I'd like
to use it to set some values in my tables on each insert/update.
Basically, I've created a mixin class (BaseMixin) which adds two fields
to each model that inherits the mixin - a user_id and a last updated
field which I want to use for audit purposes. A separate
history/versioning system will come after this.
The function attach_user_committing gets called on a flush, and in it I
can find all the newly added objects to the session by inspecting
Session._new, but I'm not sure how to determine which ones have been
updated. Any suggestions/comments on the below would be greatly
appreciated!
Thanks,
Damian
def attach_user_committing(Session, flush_context, instances):
user_id =
authenticated_userid(pyramid.threadlocal.get_current_request())
#for each object being committed/flushed, set the flushing/commiting
user
for obj in Session._new.values():
obj.user_id = user_id
obj.last_updated = datetime.now()
#this event ensures that user_id & lastupdate is correctly updated on
each flush.
event.listen(Session, "before_flush", attach_user_committing)
#We add lastupdate and userid fields (and mappings)
#to the base class for inheritance
class BaseMixin(object):
@sa.ext.declarative.declared_attr
def user_id(cls):
return sa.Column(sa.Integer, sa.ForeignKey('users.id'),
nullable=False)
@sa.ext.declarative.declared_attr
def last_update_date(cls):
return sa.Column(sa.DateTime,
default=datetime.now())
@sa.ext.declarative.declared_attr
def user(cls):
return orm.relationship('User')
--
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.