django - update date automatically after a value change

Submitted 4 years, 6 months ago
Ticket #194
Views 486
Language/Framework Django
Priority Low
Status Closed

Viewed 15k times

In the following django model:

class MyModel(models.Model):
    published = models.BooleanField(default=False)
    pub_date = models.DateTimeField('date published')

I want the pub_date field to be automatically updated with the current date, every time the published field changes to True.

Submitted on Oct 04, 20
add a comment

1 Answer

Verified

@app.task
def set_race_as_inactive(race_object):
    """
    This celery task sets the 'is_active' flag of the race object 
    to False in the database after the race end time has elapsed.
    """

    race_object.is_active = False # set the race as not active 
    race_object.save() # save the race object 

After creating the celery task set_race_as_inactive, we need to call this celery task.

We will call this task whenever we save a new race_object into our database. So, whenever a newrace_object will be saved, a celery task will be fired which will execute only after the end_time of the race_object.

We will call the task using apply_async() and pass the eta argument as the end_time of the race_object.

from my_app.tasks import set_race_as_inactive

class RaceModel(models.Model):

    ...

    def save(self, *args, **kwargs):
        ..
        create_task = False # variable to know if celery task is to be created
        if self.pk is None: # Check if instance has 'pk' attribute set 
            # Celery Task is to created in case of 'INSERT'
            create_task = True # set the variable 

        super(RaceModel, self).save(*args, **kwargs) # Call the Django's "real" save() method.

        if create_task: # check if task is to be created
            # pass the current instance as 'args' and call the task with 'eta' argument 
            # to execute after the race `end_time`
            set_race_as_inactive.apply_async(args=[self], eta=self.end_time) # task will be executed after 'race_end_time'

Submitted 4 years, 6 months ago


Latest Blogs