我有一个模型:
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()
我已经为所有三个类别创建了对象。现在我想禁止我的同事创建另一个已经存在的对象。这怎么可能?我用谷歌搜索但似乎找不到一些东西......
最佳答案
为 cat
字段设置 unique=True
( 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’ssave()
method.
cat = models.CharField(max_length=2, choices=CATS, unique=True)
关于python - Django Admin - 如何禁止创建已经存在的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23089661/