我希望在使用Falsk-SQLAlachemy将对象的属性插入数据库之前更改该对象的属性。我尝试使用before_models_committed信号,但它似乎被破坏了,所以我尝试使用models_commited(并重新提交更改),我收到以下错误:
InvalidRequestError:此会话已提交'州;没有进一步的 SQL可以在此事务中发出。
代码如下:
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)
当新对象插入数据库并保存这些更改时,有没有办法连接任何信号来执行函数?
谢谢!
答案 0 :(得分:3)
好的,我设法使用SQLAlchemy Mapper Events。
此代码:
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)
应替换为此代码:
def on_foo_created(mapper, connection, foo_obj):
foo_obj.foo_attr = get_new_value()
event.listen(Foo, 'before_insert', on_foo_created)
新的import语句是:
from flask.ext.sqlalchemy import event