2014-11-06 53 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不会向数据库发送任何附加查询。