{DetachedInstanceError}父实例<car>未绑定到会话;属性&#39;所有者的延迟加载操作&#39;无法继续</car>

时间:2014-12-30 07:52:12

标签: python sqlalchemy

我收到错误消息: {DetachedInstanceError}父实例未绑定到会话;属性“所有者”的延迟加载操作无法继续

我的python代码:

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

我的模特:

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)

这是否与Car和User(多对一关联)之间的延迟加载关系设置有关?我该如何解决这段关系?提前谢谢。

2 个答案:

答案 0 :(得分:3)

我跟踪了文档并通过添加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

答案 1 :(得分:2)

通过在joinedload_all()中添加session.query(Car).options()使其成功,例如:

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