Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - update date automatically after a value change

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.

What is the smart way?

Thanks.

like image 797
ilstam Avatar asked Aug 06 '15 14:08

ilstam


People also ask

How do I change the date automatically changes in a value in Django?

You want to add the auto_now field and set it to True. This will update with the current timestamp each time you update the model.

How can get current date in Django model?

First, open the views.py file of your Django application and import the datetime module. Next, use the datetime. now() method to get the current date and time value.

How is date stored in Django?

DateField is a field that stores date, represented in Python by a datetime. date instance. As the name suggests, this field is used to store an object of date created in python.

What is timestamped model in Django?

TimeStampedModel - An Abstract Base Class model that provides self-managed created and modified fields.


2 Answers

You want to add the auto_now field and set it to True. This will update with the current timestamp each time you update the model.

pub_date = models.DateTimeField('date_published', auto_now=True)

You can read about it here


Edit

Sorry you really just want to change the timestamp when the value of published is set to True. A really easy way to do this is to get the original value of the model and then override the save method so that it gets updated when it is set to True. Here is what you add to your code:

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

    def __init__(self, *args, **kwargs):
        super(MyModel, self).__init__(*args, **kwargs)
        self._published = self.published

    def save(self, *args, **kwargs):
        if not self._published and self.published:
            self.pub_date = django.timezone.now()
        super(MyModel, self).save(*args, **kwargs)
like image 165
Eric Bulloch Avatar answered Oct 13 '22 00:10

Eric Bulloch


All answers were useful, but I finally did it this way:

def save(self, *args, **kwargs):
    if self.published and self.pub_date is None:
        self.pub_date = timezone.now()
    elif not self.published and self.pub_date is not None:
        self.pub_date = None
    super(Model, self).save(*args, **kwargs)
like image 21
ilstam Avatar answered Oct 12 '22 23:10

ilstam