我有一个类似于以下内容的用户模型:
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.account
是 None
(这会导致错误),而我希望它是一个账户模型。 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/