使用信号时出现 django TransactionManagementError

2024-05-09

我有一个与 django 的用户和 UserInfo 一对一的字段。我想订阅用户模型上的 post_save 回调函数,以便我也可以保存 UserInfo。

@receiver(post_save, sender=User) 
def saveUserAndInfo(sender, instance, **kwargs):
    user = instance
    try:
        user.user_info.save()
    except:
        info = UserInfo()
        info.user = user
        info.save()

但是,我得到了TransactionManagementError当我尝试这样做时。我假设是因为用户模型尚未完成保存,并且我正在尝试读取 id 以将其保存到 user_info。有人知道如何正确执行此操作吗?

第二个问题。我想在创建用户后立即将 UserInfo 实例附加到用户。因此,在 post_init 上,我尝试创建一个 UserInfo 实例并将其分配给用户实例,但它不起作用,因为尚未为用户分配 pk。我假设我只需要等到 post_save (或稍后)才能创建此实例。这是唯一的方法吗?

追溯:

File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
  430.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  99.                     response = view_func(request, *args, **kwargs)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  52.         response = view_func(request, *args, **kwargs)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
  198.             return view(request, *args, **kwargs)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
  29.             return bound_func(*args, **kwargs)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  99.                     response = view_func(request, *args, **kwargs)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
  25.                 return func(self, *args2, **kwargs2)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/db/transaction.py" in inner
  339.                 return func(*args, **kwargs)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/contrib/admin/options.py" in add_view
  1129.                 self.save_model(request, new_object, form, False)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/contrib/admin/options.py" in save_model
  858.         obj.save()
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/db/models/base.py" in save
  545.                        force_update=force_update, update_fields=update_fields)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/db/models/base.py" in save_base
  582.                                    update_fields=update_fields, raw=raw, using=using)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/dispatch/dispatcher.py" in send
  185.             response = receiver(signal=self, sender=sender, **named)
File "/Users/croberts/lunchbox/userinfo/models.py" in saveUserAndInfo
  83.         info.save()
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/db/models/base.py" in save
  545.                        force_update=force_update, update_fields=update_fields)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/db/models/base.py" in save_base
  573.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
  654.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert
  687.                                using=using, raw=raw)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/db/models/manager.py" in _insert
  232.         return insert_query(self.model, objs, fields, **kwargs)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/db/models/query.py" in insert_query
  1511.     return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  898.             cursor.execute(sql, params)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/db/backends/util.py" in execute
  69.             return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/db/backends/util.py" in execute
  47.         self.db.validate_no_broken_transaction()
File "/Users/croberts/.virtualenvs/lunchbox/lib/python2.7/site-packages/django/db/backends/__init__.py" in validate_no_broken_transaction
  365.                 "An error occurred in the current transaction. You can't "

Exception Type: TransactionManagementError at /gov/auth/user/add/
Exception Value: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.

该错误是由以下原因引起的user.user_info.save()行抛出异常,并且事务被标记为已损坏(PostgreSQL 强制回滚整个事务,或在该事务内执行任何更多查询之前存储到存储的任何保存点)。

发生错误时可以回滚事务:

from django.db import IntegrityError, transaction

@receiver(post_save, sender=User) 
def saveUserAndInfo(sender, instance, **kwargs):
    user = instance
    try:
        with transaction.atomic():
            user.user_info.save()
    except IntegrityError:
        info = UserInfo()
        info.user = user
        info.save()

这在文档 https://docs.djangoproject.com/en/dev/topics/db/transactions/#django.db.transaction.atomic.

另请注意,捕获所有异常类型通常不是最好的主意,因为您可能会静音您不期望的异常。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用信号时出现 django TransactionManagementError 的相关文章

  • 如何使用 tkinter 使用网格功能显示不同的图像?

    我想使用显示文件夹中的图像grid 但是当我尝试使用以下代码时 我得到了迭代单个图像的输出 My code def messageWindow win Toplevel path C Users HP Desktop dataset for
  • 让 python 脚本打印到终端而不作为标准输出的一部分返回

    我正在尝试编写一个返回值的 python 脚本 然后我可以将其传递给 bash 脚本 问题是我想要在 bash 中返回一个单一值 但我想要一些东西一路打印到终端 这是一个示例脚本 我们称之为 return5 py usr bin env p
  • 将 numpy 数组及其大小写入二进制文件

    我需要将 2D numpy 数组写入文件 包括其尺寸 以便我可以从 C 程序中读取它并创建相应的数组 我编写了一些简单的代码来保存数组 并且可以从 C 读取它 但是如果我尝试先写入数组的大小 它总是会给我一个错误 这是我的简单 python
  • 如何检查给定的数字是否是2的幂?

    下面的代码不适用于某些输入 a i set 1 while i lt 10000 a add i i lt lt 1 N int input if N in a print True else print False 我最初的想法是检查每个
  • 如何用pygame画一条虚线?

    我需要在坐标系上绘制正弦波和余弦波 就像在this https i stack imgur com DGI8g png图片 除了没能代表以外 我所有的工作都做得很好虚线和曲线与 pygame 一致 我有与我需要的类似的东西 但我怎样才能让它
  • 在Python中,如何通过去掉括号和大括号来打印Json

    我想以一种很好的方式打印 Json 我想去掉方括号 引号和大括号 只使用缩进和行尾来显示 json 的结构 例如 如果我有一个像这样的 Json A A1 1 A2 2 B B1 B11 B111 1 B112 2 B12 B121 1
  • Python SQLite3 SQL注入漏洞代码

    我知道下面的代码片段由于 format 的原因很容易受到 SQL 注入的攻击 但我不知道为什么 有谁明白为什么这段代码容易受到攻击以及我从哪里开始修复它 我知道这些代码片段使输入字段保持打开状态 以便通过 SQL 注入执行其他恶意命令 但不
  • Flask 和 Reactjs 抛出 JSX 转换错误

    我已经开始将 ReactJS 与 Python Flask 后端结合使用 通过 Flask 渲染模板时 我在 Chrome 控制台中收到以下客户端错误 错误 找不到模块 jstransform visitors es6 templates
  • Python 模块 BeautifulSoup 提取锚点 href

    我正在使用 BeautifulSoup 模块通过以下方式从 html 选择所有 href def extract links html soup BeautifulSoup html anchors soup findAll a print
  • 如何停止 PythonShell

    如何终止 停止 Node js 中 PythonShell 执行的 Python 脚本的执行 我在交互模式下运行 输出通过 socket io 发送到给定的房间 如果没有更多的客户端连接到这个房间 我想停止 python 脚本的执行 这是我
  • python os.fork 使用相同的 python 解释器吗?

    据我所知 Python 中的线程使用相同的 Python 解释器实例 我的问题是与创建的流程相同os fork 或者每个进程创建的os fork有自己的翻译吗 每当你 fork 时 整个 Python 进程都会在内存中复制 包括Python
  • 在 Python 中引发异常的正确方法是什么? [复制]

    这个问题在这里已经有答案了 这是简单的代码 import sys class EmptyArgs StandardError pass if name main The first way to raise an exception if
  • 在添加数据之前使用 Python gdata 清除工作表中的行

    我有一个 Google 电子表格 我使用 python 脚本和 gdata 库填充值 如果我多次运行脚本 它会将新行附加到工作表中 我希望脚本在填充之前首先清除行中的所有数据 这样每次运行时我都会有一组新的数据脚本 我尝试过使用 Updat
  • 哈希 freezeset 与排序元组

    在 Python 中 给定一组可比较的 可散列的元素s 散列是否更好frozenset s or tuple sorted s 这取决于你在做什么 创建一个更快frozenset 比排序tuple but frozenset占用的内存比tu
  • 在基本 Tensorflow 2.0 中运行简单回归

    我正在学习 Tensorflow 2 0 我认为在 Tensorflow 中实现最基本的简单线性回归是一个好主意 不幸的是 我遇到了几个问题 我想知道这里是否有人可以提供帮助 考虑以下设置 import tensorflow as tf 2
  • 如何读取多个文件并将它们合并到一个 pandas 数据框中?

    我想读取位于同一目录中的多个文件 然后将它们合并到一个 pandas 数据框中 如果我这样做的话它会起作用 import pandas as pd df1 pd read csv data 12015 csv df2 pd read csv
  • 数据类和属性装饰器

    我一直在阅读 Python 3 7 的数据类 作为命名元组的替代品 我通常在必须将数据分组到结构中时使用它 我想知道数据类是否与属性装饰器兼容 以便为数据类的数据元素定义 getter 和 setter 函数 如果是这样 是否在某处进行了描
  • 根据标签位置计算 Pandas DataFrame 的索引

    我正在尝试计算标签的索引Pandas https pandas pydata org DataFrame在每一列中 基本上我有以下内容DataFrame d col1 label1 label2 label3 col2 label2 lab
  • 混合语言源目录布局

    我们正在运行一个使用多种不同语言的大型项目 Java Python PHP SQL 和 Perl 到目前为止 人们一直在自己的私有存储库中工作 但现在我们希望将整个项目合并到一个存储库中 现在的问题是 目录结构应该是什么样的 我们应该为每种
  • 从 HDF5 文件中删除信息

    我意识到 SO 用户以前曾问过这个问题question https stackoverflow com questions 1124994 removing data from a hdf5 file rq 1但它是在 2009 年被问到的

随机推荐