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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With