Change object's attribute on session commit
I want to change an object's attribute before it is inserted to the DB using Falsk-SQLAlachemy. I tried using before_models_committed signal, but it seems to be broken, so I'm trying models_commited instead (and re-committing the changes) and I get the following error:
InvalidRequestError: This session is in 'committed' state; no further SQL can be emitted within this transaction.
The code is provided bellow:
from app import db
from app import app
from flask.ext.sqlalchemy import models_committed
class Foo(db.Model):
id = db.Column(db.Integer, primary_key=True)
foo_attr = db.Column(db.String(128), index=True)
def on_models_committed(app, changes):
for change in changes:
foo_obj = change[0]
operation = change[1]
if foo_obj.__class__.__name__ == 'Foo':
if operation == 'insert':
foo_obj.foo_attr = get_new_value()
db.session.add(foo_obj)
db.session.commit()
models_committed.connect(on_models_committed)
Is there a way of connecting any signals to execute a function whenever a new object is inserted to the DB and save those changes?
Thanks!
Ok, I manage to do it using SQLAlchemy Mapper Events.
This code:
def on_models_committed(app, changes):
for change in changes:
foo_obj = change[0]
operation = change[1]
if foo_obj.__class__.__name__ == 'Foo':
if operation == 'insert':
foo_obj.foo_attr = get_new_value()
db.session.add(foo_obj)
db.session.commit()
models_committed.connect(on_models_committed)
should be replaced by this code:
def on_foo_created(mapper, connection, foo_obj):
foo_obj.foo_attr = get_new_value()
event.listen(Foo, 'before_insert', on_foo_created)
And the new import statement is:
from flask.ext.sqlalchemy import event
链接地址: http://www.djcxy.com/p/23198.html
上一篇: 映射和缩小scalaz.Lalidation的HList
下一篇: 在会话提交中更改对象的属性