如何 merge/overwrite 相同的行没有错误 sqlalchemy
How to merge/overwrite identical rows without error sqlalchemy
我有一个函数可以检查 table 中的重复行并覆盖之前的行。
过去将 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
看起来答案比我想象的要简单得多,我删除了 db.session.add(self)
并添加了:
new_obj = db.session.merge(this_usage[-1])
db.session.commit()
这似乎将最近行的值与原始行的 ID 合并了。
对于其他想知道的人 - here is some more info.
编辑:
session.merge()
停止播放多行,所以我停止使用 db.session.add(self)
并且正确提交了更改。
我有一个函数可以检查 table 中的重复行并覆盖之前的行。
过去将 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
看起来答案比我想象的要简单得多,我删除了 db.session.add(self)
并添加了:
new_obj = db.session.merge(this_usage[-1])
db.session.commit()
这似乎将最近行的值与原始行的 ID 合并了。
对于其他想知道的人 - here is some more info.
编辑:
session.merge()
停止播放多行,所以我停止使用 db.session.add(self)
并且正确提交了更改。