在SqlAlchemy中插入对象和使用id

时间:2012-10-07 11:11:32

标签: python mysql sqlalchemy

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

  

实例<位于0x457f3b0>不受会话约束;属性刷新操作无法继续

错误。

我正在使用对象填充列表并将其发送到函数以立即插入所有对象。然后我尝试使用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表。

1 个答案:

答案 0 :(得分: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(),因为你在添加对象时已经提交了会话,所以不需要它。