问题
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)
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?
回答1:
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
来源:https://stackoverflow.com/questions/28684511/can-i-use-sqlalchemy-relationships-in-orm-event-callbacks-always-get-none