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

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

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

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


当前回答

我正在使用python包psycopg2,我在查询时得到了这个错误。 我一直只运行查询,然后运行execute函数,但是当我重新运行连接(如下所示)时,它解决了这个问题。所以重新运行什么是上面你的脚本即连接,因为有人说上面,我认为它失去了连接或不同步或其他。

connection = psycopg2.connect(user = "##",
        password = "##",
        host = "##",
        port = "##",
        database = "##")
cursor = connection.cursor()

其他回答

我认为在使用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,
    }
}

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

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

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

当查询产生错误,而您试图在不先回滚事务的情况下运行另一个查询时,postgres就会这样做。(你可能会认为这是一个安全功能,防止你破坏你的数据。)

要解决这个问题,您需要找出在代码中执行错误查询的位置。在postgresql服务器中使用log_statement和log_min_error_statement选项可能会有所帮助。

在Flask shell中,我所需要做的就是一个session.rollback()来解决这个问题。

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

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

$ python manage.py syncdb

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

编码快乐!