SQLAlchemy批量更新查询因AttributeError而失败

时间:2018-06-13 09:10:52

标签: python orm sqlalchemy flask-sqlalchemy bulkupdate

以下是我的模型和关系配置,(不是一个实际的例子)

class MyUser(Base):
    __tablename__ = 'my_user'
    id = Column(Integer, primary_key=True)
    name = Column(String)


class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    email = Column(String)
    my_user = relationship("MyUser", backref="addresses", cascade='save-update, merge')
    _my_user_id = Column('my_user_id', Integer, ForeignKey('my_user.id'), nullable=True)


>>> user = db_session.query(User).get(6)
>>> add = models.Address(email='test2@test2.test2', my_user=user)
>>> db_session.add(add)
>>> db_session.commit()
>>> db_session.query(models.Address).filter_by(my_user=user).update(values=dict(email='test3@test3.test3'))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<hidden>/lib64/python3.6/site-packages/sqlalchemy/orm/query.py", line 3345, in update
        update_op.exec_()
      File "<hidden>/lib64/python3.6/site-packages/sqlalchemy/orm/persistence.py", line 1178, in exec_
        self._do_pre_synchronize()
      File "<hidden>/lib64/python3.6/site-packages/sqlalchemy/orm/persistence.py", line 1254, in _do_pre_synchronize
        query.session.identity_map.items()
      File "<hidden>/lib64/python3.6/site-packages/sqlalchemy/orm/persistence.py", line 1256, in <listcomp>
        eval_condition(obj)]
      File "<hidden>/lib64/python3.6/site-packages/sqlalchemy/orm/evaluator.py", line 109, in evaluate
        right_val = eval_right(obj)
      File "<hidden>/lib64/python3.6/site-packages/sqlalchemy/orm/evaluator.py", line 65, in <lambda>
        return lambda obj: get_corresponding_attr(obj)
    AttributeError: 'Address' object has no attribute 'my_user_id'

这时工作正常,

>>> db_session.query(models.Address).filter_by(my_user=user).update(values=dict(email='test3@test3.test3'), synchronize_session=False)
>>> db_session.query(models.Address).filter_by(_my_user_id=user.id).update(values=dict(email='test3@test3.test3'))

即使它在会话结束后也能正常工作,

>> db_session.close()
>>> db_session.query(models.Address).filter_by(my_user=user).update(values=dict(email='test3@test3.test3'))

更新查询有问题吗?为什么它适用于其他情况?

1 个答案:

答案 0 :(得分:2)

这是SQLAlchemy中的issue 3366&lt; 1.2.x,fixed in the 1.2.x series

  

Query.update()Query.delete()使用的“评估”策略现在可以容纳从多对一关系到实例的简单对象比较,当主键/外语的属性名称时键列与列的实际名称不匹配。以前,这将执行简单的基于名称的匹配,并使用AttributeError失败。

最简单的解决方案是在执行批量操作时升级或避免使用synchronizing the session的“评估”策略:

db_session.query(models.Address).\
    filter_by(my_user=user).\
    update(values=dict(email='test3@test3.test3'),
           synchronize_session=False)
# ... or 'fetch'