views:

41

answers:

2

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.

A: 

in the view

try:
    Category.objects.get(name='name')
except Category.DoesNotExist:
    # call the save method of model
Ashok
@Ashok Where would I write this? Would this be in the `save` method of the Model or the `clean_name` method?
Mridang Agarwalla
in the view, that handles the request
Ashok
+1  A: 

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.

msanders
from the OP, "I'd like to implement via code and not the DB"
Ashok
Hmmmm, OK... but your answer also reads from the DB with .get() - or am I interpreting 'not the DB' too literally? :-)
msanders
Just out of curiosity. Is there a case-insensitive unique contraint in the Django models?
Mridang Agarwalla
I don't think so. Interestingly it appears if you're using MySQL with utf-8 columns, you will already be getting case-insensitive constraints: http://docs.djangoproject.com/en/dev/ref/databases/#collation-settings
msanders