在SQLAlchemy和Python中更新表中的记录

6 投票
1 回答
9596 浏览
提问于 2025-04-16 03:56

我在尝试更新一些表格中的信息时遇到了一些问题。比如,我有这样一个表格:

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”是可以正常工作的。

有没有什么想法?

提前谢谢你!

1 个回答

0

我觉得你的代码应该是下面这两种之一:

for chan in channels:
    if rChannel.id == channel.id:
        runtime = channel.runtime

或者

for chan in channels:
    if rChannel.id == channel.id:
         for item in channel.items:
            if item.id == 0:
                rChannel.items.append(item)

但不能同时使用这两种。 我注意到你把 channel.items 加了两次到 rChannel.items 里。

撰写回答