简体   繁体   English

现在在时间间隔内更改BooleanField值

[英]Change BooleanField value when now within time interval

I have a model: 我有一个模型:

class Track(models.Model):
     act_time_start = models.DateField(null=True)
     act_time_finish = models.DateField(null=True)
     active = models.BooleanField(default=False)

What is the best practice of making active = True when now is between act_time_start and act_time_finish ? 当现在active = True act_time_startact_time_finish之间时,使active = True的最佳实践是什么? Thanks! 谢谢!

This will work, override the save() method of Model 这将起作用,重写Model的save()方法

import datetime 

NOW = datetime.date.today()
# it can be datetime.datetime.now() in case of using models.DateTimeField


class Track(models.Model):
    act_time_start = models.DateField(null=True) # Use DateTimeField for comparison with date and time
    act_time_finish = models.DateField(null=True)
    active = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        if self.pk is None:
            # Ensure that act_time_start and act_time_finish have date value
            # i.e: if isinstance(self.act_time_start,datetime.date)
            # 
            if self.act_time_start < NOW and NOW > self.act_time_finish:
                self.active = True
        super(Track, self).save(*args, **kwargs)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM