Django: How to automatically change a field's value at the time mentioned in the same object?

后端 未结 5 1117
抹茶落季
抹茶落季 2020-12-23 23:01

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)

5条回答
  •  萌比男神i
    2020-12-23 23:43

    Assuming the following scenarios -

    1. You want to be Database independent
    2. Once a race ends it never start again, so once 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.

提交回复
热议问题