首页 > 解决方案 > 如何在没有错误的情况下合并/覆盖相同的行 sqlalchemy

问题描述

我有一个函数可以检查表中的重复行并覆盖以前的行。

过去将 id 移动到另一行时它对我有用,但现在发生此错误:

raise orm_exc.FlushError(
sqlalchemy.orm.exc.FlushError: New instance <Usage at 0x7fb3f2a035e0> 
with identity key (<class 'blueprints.site.usage.Usage'>, (859,), None) 
conflicts with persistent instance <Usage at 0x7fb3d896ee50>

当我为更新的行分配一个新的 id 时,没有错误。如何将旧 ID 重新分配给新行?

def save_as_single_row(self):
    """
    Save usage as a single row in usage table.
    """
    query = Usage.query.filter_by(site_id=self.site_id, invoice_num=self.invoice_num, 
    supply_charge=self.supply_charge)
    this_usage = query.all()
    if not this_usage or (len(this_usage) == 1 and this_usage[0] == self):
        print(self.start_date, 'self')
        self.save()
        print(self.start_date)
        return self

    print('Usage already exists', this_usage[-1].__dict__)
    self.id = this_usage[-1].id
    self.credit = this_usage[-1].credit
    self.awaiting_bill_combine = this_usage[-1].awaiting_bill_combine
    self.awaiting_site_combine = this_usage[-1].awaiting_site_combine
    query.delete()
    db.session.add(self)
    db.session.commit()
    return self

标签: pythonsqlalchemyflask-sqlalchemy

解决方案


看起来答案比我想象的要简单得多,我删除db.session.add(self)并添加了:

    new_obj = db.session.merge(this_usage[-1])
    db.session.commit()

似乎这将最新行的值与原始行的 id 合并。

对于其他想知道的人-这里有更多信息。

编辑:

session.merge()停止播放多行,所以我停止使用db.session.add(self)并且正确提交了更改。


推荐阅读