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...

有帮助吗?

解决方案

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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top