在SQLAlchemy和Python中更新表中的记录
我在尝试更新某些表中的信息时遇到一些问题。例如,我有以下表格:在SQLAlchemy和Python中更新表中的记录,python,sqlalchemy,Python,Sqlalchemy,我在尝试更新某些表中的信息时遇到一些问题。例如,我有以下表格: class Channel(rdb.Model): rdb.metadata(metadata) rdb.tablename("channels") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) hash = Column("hash", String(50)) ru
class Channel(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("channels")
id = Column("id", Integer, primary_key=True)
title = Column("title", String(100))
hash = Column("hash", String(50))
runtime = Column("runtime", Float)
items = relationship(MediaItem, secondary="channel_items", order_by=MediaItem.position, backref="channels")
我有这个密码:
def insertXML(channels, strXml):
channel = Channel()
session = rdb.Session()
result = ""
channel.fromXML(strXml)
fillChannelTemplate(channel, channels)
rChannel = session.query(Channel).get(channel.id)
for chan in channels:
if rChannel.id == channel.id:
rChannel.runtime = channel.runtime
for item in channel.items:
if item.id == 0:
rChannel.items.append(item)
当我执行“rChannel.items.append(item)”时,出现以下错误:
"FlushError: New instance Channel at 0xaf6e48c with identity key
zeppelinlib.channel.ChannelTest.Channel , (152,) conflicts with
persistent instance Channel at 0xac2e8ac"
但是,此指令在“rChannel.runtime=channel.runtime”中运行
有什么想法吗
提前感谢我认为您的代码应该是:
for chan in channels:
if rChannel.id == channel.id:
runtime = channel.runtime
或
但不是两者都有。
在我看来,您正在将
频道.items
两次添加到rChannel.items
我怀疑您混合了持久的
和暂时的(或分离的)
具有相同ID的对象。当您尝试复制
相关对象时,您会遇到冲突。合并()可能会帮助您解决此问题。谢谢!数据库已更新,但我得到了相同的错误:FlushError:identity key(,(152,))的新实例与持久实例冲突。有什么想法吗?
for chan in channels:
if rChannel.id == channel.id:
for item in channel.items:
if item.id == 0:
rChannel.items.append(item)