I am working on a django project for racing event in which a table in the database has three fields.
1)Boolean field to know whether race is active or not
2)
Assuming the following scenarios -
active
is false
it will never be true
again.There are numerous ways you can set that true automatically depending on your need -
If you need only when using the object, you can use a property -
@property
def active(self):
return self.end_date > datetime.datetime.utcnow() //I used local time if you want
you can also put it in the init -
def __init__(self):
super().__init__()
self.active = self.end_date > datetime.datetime.utcnow()
But this does not give you the option to perform query, because value is calculated after object is loaded in memory.
If you want to perform query, so we need to update the value in the database and save it. Assuming that when the race ends, you update the date in the overridden save method -
def save(self, *args, **kwargs):
self.active = self.end_date > datetime.datetime.utcnow()
super().save()
So when you save the object after the race ends, it will update the flag.
But if it is not possible for you to update the race when it ends and you need them to be calculated automatically you could use a scheduler. Like Celery
as @rahul suggested to update periodically. But for this option, you have to accept the fact that, the active
flag will not be updated at the exact time of the game ends. It will depend on how frequently you run the scheduler.