Question

I have a Model:

class Category(models.Model):
CATS = (
    ('CT', 'Cool Things'),
    ('II', 'Internet & IT'),
    ('BT', 'Beautiful Things'),
)
cat = models.CharField(max_length=2, choices=CATS)
def __unicode__(self):
    return self.get_cat_display()

I have created objects to all three categories. Now I want to forbid my co-workers to create another object which already exists. How is it possible? I googled but cannot seem to have found something...

Était-ce utile?

La solution

Set unique=True for a cat field (docs):

This is enforced at the database level and by model validation. If you try to save a model with a duplicate value in a unique field, a django.db.IntegrityError will be raised by the model’s save() method.

cat = models.CharField(max_length=2, choices=CATS, unique=True)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top