我得到了:
sqlalchemy.exc.InvalidRequestError: Object '<DBEdge at 0x103c4a190>' is already attached to session '1' (this is '2')
在这一行
session.add(edge)
当我试图运行时:
def findOrCreateEdge(self,user1,user2): #user1 is followed by user2
if user1.id>user2.id:
user1, user2 = user2, user1
kind = 2
else:
kind = 1
edge = self.findEdge(user1,user2)
if edge:
if edge.kind==1 and kind==2:
edge.kind = 3
if edge.kind==2 and kind==1:
edge.kind = 3
return edge
else:
edge = DBEdge(user1,user2)
edge.kind = kind
user1.edge_count = user1.edge_count + 1
user2.edge_count = user2.edge_count + 1
#session.save(edge) # we don't flush edges here, because it gives us a huge speedup to do a bunch at once then flush.
try:
session.add(edge)
session.commit()
except:
session = Session()
session.add(edge)
session.commit()
return edge
答案 0 :(得分:3)
问题在于将边缘添加两次,一次添加到第一个会话,然后在异常时添加到第二个会话。我不知道你究竟想要在这里实现什么,但是如果你调查错误并解决了问题,那么不是粗暴地将边缘填充到新的会话中。或者,您可能希望回滚前一个会话并重新启动它,然后向其添加边缘。
当你已经拥有一个新会话时,创建一个新会话几乎总是一个错误(除非上下文本身发生了变化,但这似乎并非如此)。