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.

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hmmmm, OK... but your answer also reads from the DB with .get() - or am I interpreting 'not the DB' too literally? :-)
Just out of curiosity. Is there a case-insensitive unique contraint in the Django models?
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: docs.djangoproject.com/en/dev/ref/databases/#collation-settings
-1

in the view

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

2 Comments

Where would I write this? Would this be in the save method of the Model or the clean_name method?
in the view, that handles the request

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.