Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updated at field in django model

Tags:

python

django

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?

like image 506
Tyler Avatar asked Jun 27 '15 19:06

Tyler


People also ask

How do I update model fields in Django?

Use update_fields in save() If you would like to explicitly mention only those columns that you want to be updated, you can do so using the update_fields parameter while calling the save() method. You can also choose to update multiple columns by passing more field names in the update_fields list.

What is __ str __ In Django model?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

How do I add a field to an existing model in Django?

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB.

How Django knows to update VS insert?

The doc says: If the object's primary key attribute is set to a value that evaluates to True (i.e. a value other than None or the empty string), Django executes an UPDATE. If the object's primary key attribute is not set or if the UPDATE didn't update anything, Django executes an INSERT link.


1 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
    """
like image 118
Pieter Hamman Avatar answered Sep 19 '22 14:09

Pieter Hamman