0

我有一个表并用对象列表填充它,然后我需要使用他们的 ID,但我得到一个

实例 <location at 0x457f3b0> 未绑定到 Session;属性刷新操作无法进行

错误。

我正在用对象填充一个列表并将其发送到一个函数以一次插入所有对象。然后我尝试使用 ID。

这是我的全部插入功能:

def insertlocations(locationlist):
    session.add_all(locationlist)
    session.commit()
    session.close()

然后我尝试获取 ID:

insertlocations(neighbourhoodlist)
session.flush(neighbourhoodlist)
for neighbourhood in neighbourhoodlist:
    print neighbourhood.locationid

顺便说一下,会话是全球性的。需要任何进一步的信息吗?

正如我在 MySQL 表中查看的那样,插入了数据。

4

1 回答 1

0

您的问题很可能是您已经在函数close()中使用了会话。insertlocations()

当您随后访问neighbourhood.locationid时,会话将关闭,并且该neighbourhood对象不再绑定到会话。

例如,这应该有效:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///example.db')
engine.echo = True
Base = declarative_base()

class Location(Base):
    __tablename__ = 'locations'

    locationid = Column(Integer, primary_key=True)
    name = Column(String)
    address = Column(String)

    def __init__(self, name, address):
        self.name = name
        self.address = address


Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

def insertlocations(locationlist):
    session.add_all(locationlist)
    session.commit()


loc1 = Location('loc1', 'Foostreet 42')
loc2 = Location('loc2', 'Barstreet 27')

neighbourhoodlist = [loc1, loc2]

insertlocations(neighbourhoodlist)
for neighbourhood in neighbourhoodlist:
    print neighbourhood.locationid

session.close()
  • 退出session.close()您的功能,并在您使用完该会话后执行此操作。
  • 放弃 session.flush(),因为在添加对象时已经提交了会话,所以不需要它。
于 2012-10-07T11:22:03.193 回答