Flask-Sqlalchemy批量更新或删除报错的问题

  • Post author:
  • Post category:其他


设置synchronize_session为False可以解决

model_obj.filter(**filter_param).update(update_param, synchronize_session=False)

探究一下

synchronize_session默认是evaluate

#site-packages/sqlalchemy/orm/query.py 
def update(self, values, synchronize_session="evaluate", update_args=None):
	...
	:param synchronize_session: chooses the strategy to update the
         attributes on objects in the session. Valid values are:

            ``False`` - don't synchronize the session. This option is the most
            efficient and is reliable once the session is expired, which
            typically occurs after a commit(), or explicitly using
            expire_all(). Before the expiration, updated objects may still
            remain in the session with stale values on their attributes, which
            can lead to confusing results.

            ``'fetch'`` - performs a select query before the update to find
            objects that are matched by the update query. The updated
            attributes are expired on matched objects.

            ``'evaluate'`` - Evaluate the Query's criteria in Python straight
            on the objects in the session. If evaluation of the criteria isn't
            implemented, an exception is raised.

            The expression evaluator currently doesn't account for differing
            string collations between the database and Python.
	...
	update_op = persistence.BulkUpdate.factory(
            self, synchronize_session, values, update_args
        )
    ...

synchronize_session的实际操作对于update和delete大同小异,都是在操作的前后做操作

#site-packages/sqlalchemy/orm/persistence.py
class BulkUpdate(BulkUD):
    """BulkUD which handles UPDATEs."""

    def __init__(self, query, values, update_kwargs):
        super(BulkUpdate, self).__init__(query)
        self.values = values
        self.update_kwargs = update_kwargs

    @classmethod
    def factory(cls, query, synchronize_session, values, update_kwargs):
        return BulkUD._factory(
            {
                "evaluate": BulkUpdateEvaluate,
                "fetch": BulkUpdateFetch,
                False: BulkUpdate,
            },
            synchronize_session,
            query,
            values,
            update_kwargs,
        )
   ...

TODO:

具体报错的原因?



版权声明:本文为weixin_43262264原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。