【发布时间】:2010-11-30 02:52:30
【问题描述】:
假设我的 models.py 是这样的:
class Character(models.Model):
name = models.CharField(max_length=255)
is_the_chosen_one = models.BooleanField()
我只希望我的一个 Character 实例拥有 is_the_chosen_one == True 并且所有其他实例拥有 is_the_chosen_one == False 。我怎样才能最好地确保遵守这个唯一性约束?
考虑到尊重数据库、模型和(管理员)表单级别约束的重要性的答案的最高分!
【问题讨论】:
-
好问题。我也很好奇是否可以设置这样的约束。我知道,如果您只是将其设置为唯一约束,您最终将在数据库中只有两个可能的行;-)
-
不一定:如果您使用 NullBooleanField,那么您应该能够拥有:(一个 True,一个 False,任意数量的 NULL)。
-
根据my research、@semente 的回答,考虑到尊重数据库、模型和(管理员)表单级别约束的重要性,同时它甚至为@987654327 提供了一个很好的解决方案@ 需要
unique_together约束的ManyToManyField表。
标签: database django django-models django-admin django-forms