{DetachedInstanceError} Parent instance <Car> is not bound to a session; lazy load operation of attribute 'owner' cannot proceed
10,173
Solution 1
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
Solution 2
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
Related videos on Youtube
Author by
user3778914
Updated on September 15, 2022Comments
-
user3778914 over 1 year
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.
-
Paul Lo over 9 years
-