2014-11-06 49 views
0

我有這些模型:引發ArgumentError在joinedload

class User(UserMixin, db.Model): 
    __tablename__ = 'users_user' 
    ... 
    country = db.Column(db.Integer, db.ForeignKey('countries.id')) 


class Country(db.Model): 
    __tablename__ = 'countries' 
    id = db.Column(db.Integer, primary_key=True) 
    ... 
    user_country = db.relationship('User', backref='user_country', lazy='joined') 

我想這個查詢:

User.query.options(joinedload(Country.user_country)).filter_by(id=current_user.get_id()).first() 

這將引發此錯誤:

ArgumentError: Can't find property 'user_country' on any entity specified in this Query. 
Note the full path from root (Mapper|User|users_user) to target entity must be specified. 

什麼是錯的這裏?

+0

爲什麼不使用'current_user.user_country'? – dirn 2014-11-06 01:42:02

回答

3

這裏的joinedload是不必要的。

默認情況下,關係是延遲加載的。這會導致發出額外的SELECT查詢來檢索數據。 joinedload是通過改用JOIN來強制關係加載的方法之一。

但是,在這種情況下,您已默認UserCountry之間的關係,以便通過指定lazy='joined'來使用加載加載。這將您的查詢降低

User.query.filter(id=current_user.get_id()).first() 

雖然這會幫助你的ArgumentError,我們可以去遠一點。查詢本身也是不必要的。由於渴望加入,current_user已經擁有與其相關的Country的數據。訪問current_user.user_country不會向數據庫發送任何附加查詢。