Postgresql由于并发更新而无法序列化访问,如何找出原因

Postgresql Could not serialize access due to concurrent update, how to find out why

项目使用 Django 和 Postgresql 9.5。有时我看到芹菜任务中的错误。

当对象需要更改指定的列时,它使用 celery 任务。
此任务写入单独的 table 对象的更改历史记录和更新列(不是原始的 SQL,由 Django ORM 提供)。 Task write history by FDW extension into the foreign table.

抛出异常: Remote SQL command: COMMIT TRANSACTION\nSQL statement "SELECT 1 FROM ONLY "public"."incident_incident" x WHERE "id" OPERATOR(pg_catalog.=) FOR KEY SHARE OF x"\n',)

我不明白为什么会引发异常。任务很简单

屏幕日志(也许有帮助):

在 celery 中,当你进行交易时,你可以使用 transaction.atomic 块来完成。

例如:

@app.task(bind=True)
def do_task(self)
    try:
        with transaction.atomic():
           # Do DB OP
    except (SomeException,Exception) as exc:
        raise self.retry(exc=exc)

还有其他方法。您可以在模型中添加一个关于对象更改的新字段并跟踪它。您可以阅读this article on medium regarding this approach。希望对你有帮助!!