2015-02-23 54 views
3

我有一個用戶模型,如下所示:我可以在ORM事件回調中使用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設置正確,它只是看起來像關係引用沒有按預期工作。

這是什麼原因引發的任何想法?

回答

1

手動創建對象時,該關係不會由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 
相關問題