我可以在ORM事件回调中使用SQLAlchemy关系吗?总是无 [英] Can I use SQLAlchemy relationships in ORM event callbacks? Always get None
问题描述
我有一个类似于以下内容的用户模型:
I have a User model that resembles the following:
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
时被调用,但是当我希望它成为Account模型时,target.account
是None
(这会导致错误). target.account_id
设置正确,似乎关系引用没有按我期望的那样工作.
Upon insert after_user_write
is being called, but target.account
is None
(which causes an error) when I expect it to be an Account model. target.account_id
is set correctly, it just seems like the relationship reference isn't working as I'd expect.
关于什么原因的任何想法?
Any ideas on what's causing this?
推荐答案
手动创建对象时,SQLAlchemy不会自动设置该关系.如果要在事件回调中访问account
,请在创建User
实例时进行设置:
The relationship doesn't get set by SQLAlchemy automatically when manually creating objects. If you want to access account
in the event callback, set it when you create the User
instance:
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
这篇关于我可以在ORM事件回调中使用SQLAlchemy关系吗?总是无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!