anvd
anvd

Reputation: 4047

ArgumentError in joinedload

I have these models:

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')

I am trying this query:

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

That will throw this error:

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.

What is wrong here?

Upvotes: 0

Views: 416

Answers (1)

dirn
dirn

Reputation: 20739

The joinedload here is unnecessary.

By default relationships are lazily-loaded. This causes additional SELECT queries to be issued to retrieve the data. joinedload is one of the ways to force the relationship to be eagerly loaded by using a JOIN instead.

In this case, however, you've defaulted the relationship between User and Country to use eager loading by specifying lazy='joined'. This would reduce your query to

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

While this will help you with the ArgumentError, we can go a little further. The query itself is unnecessary as well. current_user already has the data for its related Country because of the eager join. Accessing current_user.user_country will not send any additional queries to the database.

Upvotes: 3

Related Questions