Updated on the field in django model

I have an update_at field in a django model that looks like this:

class Location(models.Model): updated_at = models.DateTimeField(auto_now=True, default=timezone.now()) 

If the model was just created, it saves the current time when the model was first created in the updated_at field. I use this to do something special if the model has been updated in the last hour. The problem is that I want to do this only if the model has been updated in the last hour, if the model has not been created. How can I differentiate if the model was updated in the last hour or if the model was created in the last hour?

+5
source share
1 answer

I would just have 2 fields on the model, one for the created ones and one that records the updated time like this

 class Location(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) 

If you use django-model-utils, you can subclass TimeStampedModel, which has both created and modified fields.

 #Django model utils TimeStampedModel class TimeStampedModel(models.Model): """ An abstract base class model that provides self-updating ``created`` and ``modified`` fields. """ created = AutoCreatedField(_('created')) modified = AutoLastModifiedField(_('modified')) class Meta: abstract = True class Location(TimeStampedModel): """ Add additional fields """ 
+11
source

All Articles