Unique BooleanField value in Django?

前端 未结 13 856
清酒与你
清酒与你 2020-12-07 14:11

Suppose my models.py is like so:

class Character(models.Model):
    name = models.CharField(max_length=255)
    is_the_chosen_one = models.BooleanField()
         


        
13条回答
  •  鱼传尺愫
    2020-12-07 14:42

    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)
    

提交回复
热议问题