D. Make
D. Make

Reputation: 600

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? Thanks!

Upvotes: 0

Views: 44

Answers (1)

Lemayzeur
Lemayzeur

Reputation: 8525

This will work, override the save() method of Model

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)

Upvotes: 2

Related Questions