Kal
Kal

Reputation: 1717

In Django, how can I programmatically check that an IntegrityError is related to a particular uniqueness constraint of the model?

For example, if I have this model:

# foo/models.py
# Python standard library
from uuid import uuid4

# Django
from django.db import models


class Foo(models.Model):
    uuid_1 = models.UUIDField(default=uuid4, unique=True)
    uuid_2 = models.UUIDField(default=uuid4, unique=True)

And then I create instances of it:

# Python standard library
from uuid import uuid4

# Django
from django.db import IntegrityError

# foo app
from foo.models import Foo

const_uuid_1 = uuid4()
const_uuid_2 = uuid4()

first_foo = Foo.objects.create(uuid_1=const_uuid_1, uuid_2=const_uuid_2)

# violate `uuid_1` uniqueness
try:
    Foo.objects.create(uuid_1=const_uuid_1)
except IntegrityError as e:
    pass

# violate `uuid_2` uniqueness
try:
    Foo.objects.create(uuid_2=const_uuid_2)
except IntegrityError as e:
    pass

So how can I tell the two uniqueness violations apart, programmatically? In my application, business requirements dictate that my program is allowed to automatically handle and correct one of the violations, but not the other (which must be reported back to the user).

Upvotes: 2

Views: 910

Answers (1)

Selcuk
Selcuk

Reputation: 59315

You should be able to use the __cause__ attribute of the exception to get access to the lower level exception. According to Django documentation:

As per PEP 3134, a __cause__ attribute is set with the original (underlying) database exception, allowing access to any additional information provided.

If you are using postgresql with psycopg you can use e.__cause__.diag for more debug info.

Upvotes: 3

Related Questions