更新分离对象的问题

时间:2010-09-10 18:55:06

标签: 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))
    runtime = Column("runtime", Float)

    items = relationship(MediaItem, secondary="channel_items", order_by=MediaItem.position, backref="channels")

我有一个频道列表,但它们是分离的对象。我使用的是joinload选项,因为我有时会操纵这些对象。当我这样做时,我更新了对象。

这一次,我正在尝试向分离的通道对象添加新项。这是代码:

def insertXML(channels, strXml):
    """Insert a new channel given XML string"""
    channel = Channel()
    session = rdb.Session()
    result = ""

    channel.fromXML(strXml)
    fillChannelTemplate(channel, channels)
    if channel.id == 0:
        session.add(channel)
        session.flush()
        channels.append(channel)
    else:
        for chan in channels:
            if chan.id == channel.id:
                chan.runtime = channel.runtime
                chan.modified = datetime.date.today()

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

        session.merge(chan)

该项目已插入数据库中,但它不会在channel_items中创建关系。

此外,我收到此错误:

FlushError: New instance <Channel at 0xb75eeec> with identity key 
     (<class 'zeppelinlib.channel.ChannelTest.Channel'>, (152,)) 
     conflicts with persistent instance <Channel at 0xb598dec

这是一个问题,因为需要更新双方(服务器和数据库)中的通道,所以如果我得到错误,那么对象也不会在服务器中更新。

有什么想法吗?

0 个答案:

没有答案
相关问题