Update a record in a table in SQLAlchemy and Python

匿名 (未验证) 提交于 2019-12-03 00:55:01

问题:

I have some problems when I try to update information in some tables. For example, I have this table:

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")

And I have this code:

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)

When I do "rChannel.items.append(item)", I got this error:

"FlushError: New instance Channel at 0xaf6e48c with identity key zeppelinlib.channel.ChannelTest.Channel , (152,) conflicts with persistent instance Channel at 0xac2e8ac"

However, this instruction is working "rChannel.runtime = channel.runtime".

Any ideas?

Thanks in advance

回答1:

I think your code should be either:

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

or

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

And not both. It appears to me that your adding channel.items twice to rChannel.items.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!