2014-10-16 85 views
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) 

每當一個新對象被插入到數據庫並保存這些更改時,是否有連接任何信號來執行函數的方法?

謝謝!

回答

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 
+0

相信這裏有一個重要的區別。 'before_insert'發生在與'models_committed'不同的時刻。 [來源](https://pythonhosted.org/Flask-SQLAlchemy/signals.html#models_committed) – 2014-11-26 20:26:40

相關問題