[英]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.