【问题标题】:ArgumentError in joinedload连接加载中的参数错误
【发布时间】:2024-11-14 03:20:02
【问题描述】:

我有这些模型:

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.

这里有什么问题?

【问题讨论】:

  • 为什么不直接使用current_user.user_country

标签: python orm flask sqlalchemy flask-sqlalchemy


【解决方案1】:

这里的joinedload 是不必要的。

默认情况下,关系是延迟加载的。这会导致发出额外的SELECT 查询来检索数据。 joinedload 是通过使用 JOIN 来强制加载关系的方法之一。

但是,在这种情况下,您已通过指定 lazy='joined'UserCountry 之间的关系默认为使用预加载。这会将您的查询减少到

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

虽然这将帮助您使用ArgumentError,但我们可以走得更远。查询本身也是不必要的。 current_user 由于急切加入,已经拥有其相关 Country 的数据。访问current_user.user_country 不会向数据库发送任何额外的查询。

【讨论】:

    最近更新 更多