Django+Postgres: “current transaction is aborted, commands ignored until end of transaction block”

后端 未结 9 1470
暖寄归人
暖寄归人 2020-12-12 11:39

I\'ve started working on a Django/Postgres site. Sometimes I work in manage.py shell, and accidentally do some DB action that results in an error. Then I am una

相关标签:
9条回答
  • 2020-12-12 12:06

    You can try this:

    from django.db import connection
    connection._rollback()
    

    The more detailed discussion of This issue can be found here

    0 讨论(0)
  • 2020-12-12 12:06

    WARNING: the patch below can possibly cause transactions being left in an open state on the db (at least with postgres). Not 100% sure about that (and how to fix), but I highly suggest not doing the patch below on production databases.

    As the accepted answer does not solve my problems - as soon as I get any DB error, I cannot do any new DB actions, even with a manual rollback - I came up with my own solution.

    When I'm running the Django-shell, I patch Django to close the DB connection as soon as any errors occur. That way I don't ever have to think about rolling back transactions or handling the connection.

    This is the code I'm loading at the beginning of my Django-shell-session:

    from django import db
    from django.db.backends.util import CursorDebugWrapper
    old_execute = CursorDebugWrapper.execute
    old_execute_many = CursorDebugWrapper.executemany
    
    def execute_wrapper(*args, **kwargs):
        try:
            old_execute(*args, **kwargs)
        except Exception, ex:
            logger.error("Database error:\n%s" % ex)
            db.close_connection
    
    def execute_many_wrapper(*args, **kwargs):
        try:
            old_execute_many(*args, **kwargs)
        except Exception, ex:
            logger.error("Database error:\n%s" % ex)
            db.close_connection
    
    CursorDebugWrapper.execute = execute_wrapper
    CursorDebugWrapper.executemany = execute_many_wrapper
    
    0 讨论(0)
  • 2020-12-12 12:11

    I got this error in Django 1.7. When I read in the documentation that

    This problem cannot occur in Django’s default mode and atomic() handles it automatically.

    I got a bit suspicious. The errors happened, when I tried running migrations. It turned out that some of my models had my_field = MyField(default=some_function). Having this function as a default for a field worked alright with sqlite and mysql (I had some import errors, but I managed to make it work), though it seems to not work for postgresql, and it broke the migrations to the point that I didn't event get a helpful error message, but instead the one from the questions title.

    0 讨论(0)
提交回复
热议问题