7
我想在使用Falsk-SQLAlachemy將其插入到數據庫之前更改對象的屬性。我試着用before_models_committed信號,但它似乎被打破,所以我想models_commited代替(並重新提交修改),我收到以下錯誤:在會話提交時更改對象的屬性 - Flask SQLAlchemy
InvalidRequestError: This session is in 'committed' state; no further SQL can be emitted within this transaction.
的代碼波紋管提供:
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)
每當一個新對象被插入到數據庫並保存這些更改時,是否有連接任何信號來執行函數的方法?
謝謝!
相信這裏有一個重要的區別。 'before_insert'發生在與'models_committed'不同的時刻。 [來源](https://pythonhosted.org/Flask-SQLAlchemy/signals.html#models_committed) – 2014-11-26 20:26:40