python - 如何在没有错误的情况下合并/覆盖相同的行 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
解决方案
看起来答案比我想象的要简单得多,我删除db.session.add(self)
并添加了:
new_obj = db.session.merge(this_usage[-1])
db.session.commit()
似乎这将最新行的值与原始行的 id 合并。
对于其他想知道的人-这里有更多信息。
编辑:
session.merge()
停止播放多行,所以我停止使用db.session.add(self)
并且正确提交了更改。
推荐阅读
- c++ - AreaSeries 仅显示悬停
- yammer - 获取基于日期过滤器的对话/线程列表?
- azure - 带有 mikrotik 的 Azure 站点到站点:缺少有效负载:ID_R
- ml - 运算符和操作数不同意这个简单函数中的错误
- django - Django 看不到任何已安装的应用程序
- swift - xcode 永远继续加载项目
- puppet - 使用 puppet 从特定仓库安装软件包
- intellij-idea - 为什么 pycharm 尝试自动执行 ssh-add?
- jsf - ChartUtilities.getImageMap() 未在 JSF 中生成工具提示
- php - 自然语言实体提取