python - 我可以在 ORM 事件回调中使用 SQLAlchemy 关系吗?总是没有

标签 python sqlalchemy flask-sqlalchemy

我有一个类似于以下内容的用户模型:

class User(db.Model):

    id = db.Column(db.BigInteger, primary_key=True)
    account_id = db.Column(db.BigInteger, db.ForeignKey('account.id'))

    account = db.relationship('Account',
         backref=db.backref('ref_users', cascade='delete'))

    ...

def after_user_write(mapper, connection, target):
    target.account.invalidate_cache()

event.listen(User, 'after_insert', after_user_write)
event.listen(User, 'after_update', after_user_write)
event.listen(User, 'after_delete', after_user_write)

在调用插入 after_user_write 时,target.accountNone(这会导致错误),而我希望它是一个账户模型。 target.account_id 设置正确,关系引用似乎没有像我预期的那样工作。

关于造成这种情况的原因有什么想法吗?

最佳答案

手动创建对象时,SQLAlchemy 不会自动设置关系。如果您想在事件回调中访问account,请在创建User 实例时设置它:

a1 = Account()
u1 = User(account_id=a1.id)
db.session.add(u1)
db.session.commit()

assert u1.account is None

a2 = Account()
# Here: set the account object, instead of the id
u2 = User(account=a2)
db.session.add(u2)
db.session.commit()

assert u2.account == a2
assert u2.account_id == a2.id

关于python - 我可以在 ORM 事件回调中使用 SQLAlchemy 关系吗?总是没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28684511/

相关文章:

python - 这段 python 代码中的语法是否正确?

python - SQLAlchemy 的快速且肮脏的 CRUD 接口(interface)?

postgresql - Alembic 未生成正确的更改

python - 使用 SQLAlchemy/Alembic 时如何检查是否有挂起的迁移?

python - 如何在python flask中使用Delete方法

Python:运行一个进程/线程,即使在主进程完成后仍继续运行

python - H5py 存储字符串列表列表

Python bob 包 API - 如何格式化输入数据

python - SQLAlchemy 关系错误 : object has no attribute 'c'

python - 如何在 SQLAlchemy 中使用来自 backref(.., order_by=..) 内部混合类的列名?