Note that there are some explanatory texts on larger screens.

plurals
  1. PODuplicate save in Django transaction causing InternalError instead of IntegrityError
    primarykey
    data
    text
    <p>I am using PostgreSQL as my backend with psycopg2, and I'm noticing something that seems strange to me. My set up is as follows:</p> <pre><code>class ParentModel(models.Model): field1 = models.IntegerField() class ChildModel(ParentModel): field2 = models.IntegerField(unique=True) </code></pre> <p>When I try to save a ChildModel object with a duplicate field2 from the shell, I get an InternalError instead of an IntegrityError, but <em>only</em> if the save is done in a transaction.commit_on_success block like so:</p> <pre><code>with transaction.commit_on_success(): newObj = ChildModel(field1=5, field2=10) # Assume that a ChildModel with field2 == 10 exists </code></pre> <p>Outside of the transaction block, I get an IntegrityError, as I would expect. </p> <p>When running inside view code, I always get the InternalError following the failed update even using savepoints:</p> <pre><code>try: sid = transaction.savepoint() newObj = ChildModel(field1=5, field2=10) # Assume that a ChildModel with field2 == 10 exists transaction.savepoint_commit(sid) except IntegrityError: transaction.savepoint_rollback(sid) except InternalError: transaction.savepoint_rollback(sid) ... other stuff ... # raises InternalError on next database hit </code></pre> <p>Same thing happens if I do it within a commit_on_success transaction with block, instead of using savepoints. I have TransactionMiddleware installed and I am not running PostgreSQL in autocommit mode. </p> <p>I can avoid the situation by simply checking to make sure the duplicate object doesn't exist, but I want to udnerstand what's going wrong with my understanding of Django transactions. What gives?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload