When should I be calling flush() on SQLAlchemy?

一世执手 提交于 2019-12-03 01:49:15

The ZopeTransactionExtension on the DBSession in conjunction with the pyramid_tm being active on your project will handle all commits for you. The situations where you need to flush are:

  • You want to create a new object and get back the primary key.

    DBSession.add(obj)
    DBSession.flush()
    log.info('look, my new object got primary key %d', obj.id)
    
  • You want to try to execute some SQL in a savepoint and rollback if it fails without invalidating the entire transaction.

    sp = transaction.savepoint()
    try:
        foo = Foo()
        foo.id = 5
        DBSession.add(foo)
        DBSession.flush()
    except IntegrityError:
        log.error('something already has id 5!!')
        sp.rollback()
    

In all other cases involving the ORM, the transaction will be aborted for you upon exception, or committed upon success automatically by pyramid_tm. If you execute raw SQL, you will need to execute transaction.commit() yourself or mark the session as dirty via zope.sqlalchemy.mark_changed(DBSession) otherwise there is no way for the ZTE to know the session has changed.

Also you should leave expire_on_commit at the default of True unless you have a really good reason.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!