Mridang Agarwalla
Mridang Agarwalla

Reputation: 44988

Code based unique constraint Django Model

I have a Django model that looks like this:

class Categories(models.Model):
    """
    Model for storing the categories
    """
    name = models.CharField(max_length=8)
    keywords = models.TextField()
    spamwords = models.TextField()
    translations = models.TextField()

def save(self, force_insert=False, force_update=False):
    """
    Custom save method that converts the name to uppercase
    """
    self.name = self.name.upper()
    super(Categories, self).save(force_insert, force_update)

Whenever the data is inserted or updated. I'd like to check that that a record with same name doesn't exists. It's a unique constraint that I'd like to implement via code and not the DB. The amount of data in this table is minuscule so the the performance hit is not an issue. If there is an constraint violation, I'd like to raise one of Django's inbuilt constraint exceptions instead of creating a custom one.

Could someone how me the best/fastest way to accomplish this?

Thanks.

Upvotes: 2

Views: 7385

Answers (2)

msanders
msanders

Reputation: 5919

In your model definition you can tell Django that 'name' should be unique:

name = models.CharField(max_length=8, unique=True)

A django.db.IntegrityError will be raised if you attempt to save two records with the same name.

Upvotes: 8

Ashok
Ashok

Reputation: 10603

in the view

try:
    Category.objects.get(name='name')
except Category.DoesNotExist:
    # call the save method of model

Upvotes: -1

Related Questions