Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

{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.

like image 605
user3778914 Avatar asked Dec 30 '14 07:12

user3778914


2 Answers

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

like image 147
user3778914 Avatar answered Sep 17 '22 15:09

user3778914


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

like image 42
monkeyerkong Avatar answered Sep 21 '22 15:09

monkeyerkong