Django中的Unique BooleanField值? [英] Unique BooleanField value in Django?

查看:364
本文介绍了Django中的Unique BooleanField值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的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中的Unique BooleanField值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆