未在 sqlalchemy 中提交列更新(sqlalchemy-utils)

Column update not being commited in sqlalchemy (sqlalchemy-utils)

我有一个 User 模型,在许多其他列中有一个密码列 (PasswordType)。当我尝试这样做时

user = # get some user with some query
print(user.password)
# there is a password

user.password = 'something else'
db.session.is_modified(user)
# True
db.session.commit()
print(user.password)
# prints new password

user.password = None
db.session.is_modified(user)
# True
db.session.commit()
print(user.password)
# This correctly prints None

# Now the funny part,
user.password = 'something new again'
db.session.is_modified(user)
# False
db.session.commit()
print(user.password)
# Prints None again.

我已经处理这个问题好几个小时了,不明白为什么会这样。

这可能会回答您的问题:检查一下:http://docs.sqlalchemy.org/en/rel_0_9/orm/session_api.html#sqlalchemy.orm.session.Session.is_modified

Instances present in the Session.dirty collection may report False when tested with this method. This is because the object may have received change events via attribute mutation, thus placing it in Session.dirty, but ultimately the state is the same as that loaded from the database, resulting in no net change here.

您可能还想将其用于状态管理实用程序(以便了解您的实例所处的状态)。

>>> from sqlalchemy.orm.util import object_state
>>> print object_state(instance)

问题出在 SQLAlchemy-utils 中的 PasswordType

当我打电话给 force_auto_coercion 时它起作用了。