How to handle Django IntegrityError when working with PostgreSQL

22 August 2013

Let's say you have a case when you have to create some objects in the database, but you want to prevent duplicates. In that case, you might write

try:
    Model.objects.create(**kwargs)
except IntegrityError:
    pass

This is not enough if you use PostgreSQL, because when an error occurs the transaction is aborted. That means that all the following queries to the database will trigger an error informing you about the aborted status of the transaction. What you need to do is rollback the transaction to start fresh. The code for that is

from django.db import transaction
with transaction.commit_manually()
    try:
        Model.objects.create(**kwargs)
    except IntegrityError:
        transaction.rollback()
    else:
        transaction.commit()

This entry was tagged as technology django postgresql

blog comments powered by Disqus