python - Django Admin - 如何禁止创建已经存在的对象

标签 python django django-admin

我有一个模型:

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’s save() method.

cat = models.CharField(max_length=2, choices=CATS, unique=True)

关于python - Django Admin - 如何禁止创建已经存在的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23089661/

相关文章:

Django - 管理员 save_model() 和 post_save 信号之间的区别

python - Django 管理 "save and view on site"按钮

python - GDALWarp 返回 NULL 且未设置错误

python - 什么是 Yahoo openid 发现端点

python - django-为什么这个表单总是无效的

python - 在使用 django-filter 进行过滤时如何将过滤后的值导出到 csv 文件中

javascript - HTML 上的 Django 导航文本

django - 错误 ```禁止 (403) CSRF 验证失败。尝试登录管理员时请求中止 .`` `

python - Pandas dataframe 将行值与列名映射

python - 是否有 YSlow 的 Perl 替代品?