简体   繁体   English

如何使 boolean 字段在 Django 中只保留一个真值

[英]How to make boolean field hold only one True value in Django

Am working on a Saving scheme, I have implemented it so that it works on cycles.我正在制定一个储蓄方案,我已经实施了它,以便它可以循环使用。

Is there a way I can have only one active cycle enforced by my boolean field?有没有一种方法可以让我的 boolean 字段只执行一个活动周期?

models.py模型.py

class Cycle(models.Model):
    cycle_name =  models.CharField( max_length=220, null=True, blank=True, unique=True)
    rate = models.IntegerField(default=15, null=True, blank=True)
    cycle_period_start = models.DateField(max_length=255, blank=False, null=False, unique=True)
    cycle_period_end = models.DateField(max_length=255, blank=False, null=False, unique=True)
    is_active = models.BooleanField(default=True) 

    def __str__(self):
        return self.cycle_period_start.year + "/" + self.cycle_period_end.year

Basically what I want is that when I add new cycle, the field is_active is set to False for other cycle.基本上我想要的是,当我添加新周期时,字段is_active被设置为False用于其他周期。

Thank you for the help感谢您的帮助

So what you could do is before creating the new Cycle is to update all existing cycles that the are no longer active.因此,您可以做的是在创建新循环之前更新所有不再处于活动状态的现有循环。

Thus something like this.因此像这样的事情。

Cycle.objects.update(is_active=False)
Cycle.objects.create(is_active=True, ...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 django inlineformset,如何一次只允许1个布尔字段为真? - django inlineformset, how to allow only 1 boolean field to be true at a time? 当时只有一个布尔值允许为True吗? - Only one boolean value allowed True at the time? 如何将Django模型布尔值字段更新为true? - How to update Django model Boolean field as true? 如何知道 Django 中哪个布尔字段为真 - How to know which boolean field is true in django Django - 具有Single True的布尔字段 - Django - Boolean field with Single True 如何在Django中只保证一个布尔值对于一个具有特定ForeignKey的行? - How can I guarantee that a boolean is true for only one row with a particular ForeignKey in Django? 在 ElasticSearch 中如何检查一个字段是否存在然后应该只返回布尔值( True 或 False ) - In ElasticSearch how to check if a field exists then should return Boolean value( True or False ) only 当实例的某个字段为 True (Django) 时,如何将模型表单的字段设为只读? - How to make a field of a model form read-only when a certain field of an instance is True (Django)? 仅显示布尔字段= True,如何在模板中编写? - Only Boolean Field = True to show, How to write in the template? Django 表单 - 将布尔字段更新为 true - Django form - update boolean field to true
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM