Django 中唯一的 BooleanField 值? [英] Unique BooleanField value in Django?
问题描述
假设我的models.py是这样的:
Suppose my models.py is like so:
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
.我如何才能最好地确保遵守此唯一性约束?
I want only one of my Character
instances to have is_the_chosen_one == True
and all others to have is_the_chosen_one == False
. How can I best ensure this uniqueness constraint is respected?
考虑到尊重数据库、模型和(管理)表单级别约束的重要性的答案的最高分!
Top marks to answers that take into account the importance of respecting the constraint at the database, model and (admin) form levels!
推荐答案
每当我需要完成这个任务时,我所做的就是覆盖模型的保存方法并让它检查是否有任何其他模型具有标志已设置(并将其关闭).
Whenever I've needed to accomplish this task, what I've done is override the save method for the model and have it check if any other model has the flag already set (and turn it off).
class Character(models.Model):
name = models.CharField(max_length=255)
is_the_chosen_one = models.BooleanField()
def save(self, *args, **kwargs):
if self.is_the_chosen_one:
try:
temp = Character.objects.get(is_the_chosen_one=True)
if self != temp:
temp.is_the_chosen_one = False
temp.save()
except Character.DoesNotExist:
pass
super(Character, self).save(*args, **kwargs)
这篇关于Django 中唯一的 BooleanField 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!