在会话提交中更改对象的属性

我想在使用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)

有没有办法连接任何信号来执行一个函数,每当一个新的对象被插入到数据库并保存这些更改?

谢谢!


好吧,我设法使用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)

新的进口声明是:

from flask.ext.sqlalchemy import event
链接地址: http://www.djcxy.com/p/23197.html

上一篇: Change object's attribute on session commit

下一篇: Issue downloading report exported to PPTX when deployed on server