开发者

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 i开发者_JS百科s 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.


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.


in the view

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜