[Django]-Django, Postgresql & IntegrityErrors

8👍

It will depend on how you manage your transaction.

On Postgres if one of query in transaction fails all subsequent query will also fail with error “current transaction is aborted, queries ignored until end of transaction block”.

To deal with it you should use transaction.savepoint_rollback in an except block.

Please refer to Django doc Handling exceptions within PostgreSQL transactions

It gives the next example

a.save() # Succeeds, and never undone by savepoint rollback
try:
    sid = transaction.savepoint()
    b.save() # Could throw exception
    transaction.savepoint_commit(sid)
except IntegrityError:
    transaction.savepoint_rollback(sid)
c.save() # Succeeds, and a.save() is never undone
👤Igor

1👍

By not ignoring errors?

The code you wrote works kind of like this.

You:    Save all the things.
Django: You're about to violate data integrity in your database.
You:    I don't care.
Django: I can't simply corrupt your data. I'll just throw away 
        the things that would corrupt your data.
You:    That's what I wanted.

While that might be appropriate for some applications, it not appropriate for most.

You just need to decide what you ought to be doing with data that violates your integrity constraints, and you need to fix the code that’s allowing bad data to get to the save() method in the first place. Documentation on Form and Field Validation might help.

Leave a comment