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.
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.
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.
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.
TimeStampedModel - An Abstract Base Class model that provides self-managed created and modified fields.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With