updated at field in django model

Question:

I have an updated_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 am using this to do something special if the model was updated within the past hour. Problem is that I only want to do that if the model was updated in the past hour not if the model was created. How can I differentiate if the model was updated in the past hour or if the model was created in the past hour?

Asked By: Tyler

||

Answers:

I would just have 2 fields on the model, one for created and one that records 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 are using django-model-utils you can subclass the 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
    """
Answered By: Pieter Hamman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.