我收到了很多错误的信息:

"DatabaseError: current transaction is aborted, commands ignored until end of transaction block"

作为Django项目的数据库引擎,从python-psycopg改为python-psycopg2。

代码保持不变,只是不知道这些错误来自哪里。


当前回答

我在postgres终端上运行故障事务时遇到了类似的行为。在此之后什么都没有通过,因为数据库处于错误状态。但是,作为一个快速解决方案,如果可以避免回滚事务。以下是我的诀窍:

提交;

其他回答

您可以通过“set_isolation_level(0)”禁用事务

我也有这个错误,但它掩盖了另一个更相关的错误消息,代码试图在100个字符的列中存储125个字符的字符串:

DatabaseError: value too long for type character varying(100)

我必须调试代码才能显示上面的消息,否则就会显示

DatabaseError: current transaction is aborted

这种行为对我来说很奇怪。我很惊讶没有人想到保存点。在我的代码中,查询失败是预期的行为:

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

我认为在使用PostgreSQL时,priestc提到的模式更有可能是这个问题的常见原因。

然而,我觉得这个模式有一些有效的用途,我不认为这个问题应该成为总是避免它的理由。例如:

try:
    profile = user.get_profile()
except ObjectDoesNotExist:
    profile = make_default_profile_for_user(user)

do_something_with_profile(profile)

如果你觉得这种模式没问题,但又不想到处都是显式的事务处理代码,那么你可能会考虑开启自动提交模式(PostgreSQL 8.2+): https://docs.djangoproject.com/en/dev/ref/databases/#autocommit-mode

DATABASES['default'] = {
    #.. you usual options...
    'OPTIONS': {
        'autocommit': True,
    }
}

我不确定是否有重要的性能考虑因素(或任何其他类型)。

我也遇到了同样的问题。我在这里遇到的问题是我的数据库没有正确地同步。简单的问题似乎总是引起最大的焦虑。

要同步你的django db,在你的app目录中,在终端中,输入:

$ python manage.py syncdb

编辑:注意,如果你正在使用django-south,运行'$ python manage.py migrate'命令也可以解决这个问题。

编码快乐!