尝试更新使用外键作为主键一部分的行时,我遇到了问题。这是一个简化的案例:
class Foo(Base):
__tablename__ = 'foo_table'
foo_id = Column(Integer, primary_key=True)
bar_id = Column(Integer, ForeignKey('bar_table.bar_id'), primary_key=True)
foo_data = Column(String(255))
bar = relationship('Bar', backref='foos', foreign_keys=[bar_id])
class Bar(Base):
__tablename__ = 'bar_table'
bar_id = Column(Integer, primary_key=True)
首先,我将为foo_table
:
f = Foo()
f.foo_id = 1
f.foo_data = 'Foo Data'
现在我将在bar_table
中创建一行并将两者关联起来:
b = Bar()
f.bar = b
大!我们将f
添加到会话并提交:
session.add(f)
session.commit()
现在假装我们遇到Foo
的另一个foo_id
实例并且与同一个Bar
相关,但有一些新数据:
f = Foo()
f.foo_id = 1
f.foo_data = 'NEW Foo Data'
f.bar = b
没关系!这种情况一直都在发生,对吧?我只会使用foo_table
代替session.merge()
更新session.add()
中的信息:
session.merge(f)
但这不好!代码中断了,我得到了回溯:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/session.py", line 1689, in merge
self._autoflush()
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/session.py", line 1282, in _autoflush
self.flush()
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/session.py", line 2004, in flush
self._flush(objects)
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/session.py", line 2122, in _flush
transaction.rollback(_capture_exception=True)
File "/Library/Python/2.7/site-packages/sqlalchemy/util/langhelpers.py", line 60, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/session.py", line 2086, in _flush
flush_context.execute()
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/unitofwork.py", line 373, in execute
rec.execute(self)
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/unitofwork.py", line 532, in execute
uow
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/persistence.py", line 149, in save_obj
base_mapper, states, uowtransaction
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/persistence.py", line 301, in _organize_states_for_save
state_str(existing)))
sqlalchemy.orm.exc.FlushError: New instance <Foo at 0x10a804590> with identity key (<class 'test.Foo'>, (1, 1)) conflicts with persistent instance <Foo at 0x1097a30d0>
有谁知道为什么这次更新失败了?
答案 0 :(得分:1)
我不确定是否有一个非常好的答案......我最终查询了我是否正在使用新数据。
因此,每当我创建Foo
的新实例时,
old_foo = session.query(Foo).filter(Foo.id == id).all()
if old_foo:
foo = old_foo[0]
else:
foo = Foo()
这似乎并不理想,但我还没有找到另一种有效的解决方案。