我收到了很多错误的信息:
"DatabaseError: current transaction is aborted, commands ignored until end of transaction block"
作为Django项目的数据库引擎,从python-psycopg改为python-psycopg2。
代码保持不变,只是不知道这些错误来自哪里。
我收到了很多错误的信息:
"DatabaseError: current transaction is aborted, commands ignored until end of transaction block"
作为Django项目的数据库引擎,从python-psycopg改为python-psycopg2。
代码保持不变,只是不知道这些错误来自哪里。
当前回答
这种行为对我来说很奇怪。我很惊讶没有人想到保存点。在我的代码中,查询失败是预期的行为:
from django.db import transaction
@transaction.commit_on_success
def update():
skipped = 0
for old_model in OldModel.objects.all():
try:
Model.objects.create(
group_id=old_model.group_uuid,
file_id=old_model.file_uuid,
)
except IntegrityError:
skipped += 1
return skipped
我用这种方式更改了代码来使用保存点:
from django.db import transaction
@transaction.commit_on_success
def update():
skipped = 0
sid = transaction.savepoint()
for old_model in OldModel.objects.all():
try:
Model.objects.create(
group_id=old_model.group_uuid,
file_id=old_model.file_uuid,
)
except IntegrityError:
skipped += 1
transaction.savepoint_rollback(sid)
else:
transaction.savepoint_commit(sid)
return skipped
其他回答
要摆脱错误,在你修复了你的代码后回滚最后一个(错误的)事务:
from django.db import transaction
transaction.rollback()
你可以使用try-except来防止错误的发生:
from django.db import transaction, DatabaseError
try:
a.save()
except DatabaseError:
transaction.rollback()
参考:Django文档
只需使用回滚
示例代码
try:
cur.execute("CREATE TABLE IF NOT EXISTS test2 (id serial, qa text);")
except:
cur.execute("rollback")
cur.execute("CREATE TABLE IF NOT EXISTS test2 (id serial, qa text);")
我在postgres终端上运行故障事务时遇到了类似的行为。在此之后什么都没有通过,因为数据库处于错误状态。但是,作为一个快速解决方案,如果可以避免回滚事务。以下是我的诀窍:
提交;
在Flask shell中,我所需要做的就是一个session.rollback()来解决这个问题。
我也遇到了同样的问题。我在这里遇到的问题是我的数据库没有正确地同步。简单的问题似乎总是引起最大的焦虑。
要同步你的django db,在你的app目录中,在终端中,输入:
$ python manage.py syncdb
编辑:注意,如果你正在使用django-south,运行'$ python manage.py migrate'命令也可以解决这个问题。
编码快乐!