user3778914
user3778914

Reputation: 393

{DetachedInstanceError} Parent instance <Car> is not bound to a session; lazy load operation of attribute 'owner' cannot proceed

I got error message: {DetachedInstanceError} Parent instance is not bound to a session; lazy load operation of attribute 'owner' cannot proceed

My python code:

car_obj = my_query_function()  # get a Car object
owner_name = car_obj.owner.name # here generate error!

My model:

class Person(EntityClass):
    attributes = ['id', 'name']

    name = sa.Column(sa.String(250))


class Car(EntityClass):
    attributes = ['id', 'brand', 'color', 'purchase_time', 'owner_id']

    brand = sa.Column(sa.String(250))
    color = sa.Column(sa.String(250))
    purchase_time = sa.Column(sa.String(250))
    owner_id = sa.Column(DBKeyType, sa.ForeignKey(Person.__tablename__ + '.id'), nullable=False)
    owner = relationship('Person', cascade='all, delete-orphan', backref=backref('car', cascade='delete'), single_parent=True)

Is this has something to do with the lazy-loading relationship setting between Car and User (many-to-one association)? How can I fix the relationship? Thanks in advance.

Upvotes: 11

Views: 13951

Answers (2)

user3778914
user3778914

Reputation: 393

I traced the docs and made it work by adding lazy='subquery'

owner = relationship('Person', lazy='subquery', cascade='all, delete-orphan', backref=backref('car', cascade='delete'), single_parent=True)

http://docs.sqlalchemy.org/en/rel_0_9/orm/join_conditions.html

Upvotes: 15

monkeyerkong
monkeyerkong

Reputation: 59

Made it work by adding joinedload_all() in session.query(Car).options(), for example:

cars = session.query(Car).options(joinedload_all('*')).all()
session.close()
for car in cars:
     "do your struff"

good luck

Upvotes: 5

Related Questions