{DetachedInstanceError} The parent <Car> instance is not attached to the session; lazy loading of the "owner" attribute cannot continue
I got an error message: {DetachedInstanceError} The parent instance is not attached to the session; lazy loading of the "owner" attribute cannot continue
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)
Does it have something to do with establishing a lazy loading relationship between Car and User (a one-to-one association)? How can I fix my relationship? Thanks in advance.
+3
source to share
2 answers
I traced the docs and did this 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
+3
source to share