Django Timestamp without using auto_now and auto_now_add

If you have ever used/worked on CMS/Blogging apps, you might have noticed created and last updated timestamp’s for each content item (article/entry) and as you would expect Django also provide two options for DateTimeField which will enable you to create timestamps automatically. DateTimeField with option auto_now_add ( models.DateTimeField(auto_now_add=True) ) can be used for created timestamp while DateTimeField with option auto_now ( models.DateTimeField(auto_now=True) ) can be used for last updated timestamp. Only drawback of auto_now and auto_now_add is they disable editing timestamps from admin.

Well I think auto_now and auto_now_add are often used in development but for some reason Django core developers want to get rid of that and most likely auto_now and auto_now_add will be removed in version 2.0 (As mentioned during Django Technical Design, Djangocon 2008, video embedded below).  May be they want to reduce core size by removing the code which can be implemented easily or improve the same with new TimeStampField (Hinted by James Bennett during the same discussion, though I agree with Russel Keith having it doesn’t hurt)  but still no clarity if auto_now and auto_now_add will be part of Django 2.0 or not and I think one should avoid using them.

It’s easy to achieve the same by overriding save method as shown below using example model. ( Most of the code is self explanatory and focus should be on created and updated fields)

Before (with auto_now and auto_now_add) :

1
2
3
4
5
6
7
8
9
class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(blank=True)
    content = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
 
    def __unicode__(self):
        return self.title

After( Same functionality without auto_now and auto_now_add ):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from datetime import datetime
class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(blank=True)
    content = models.TextField()
    created = models.DateTimeField(editable=False)
    updated = models.DateTimeField(editable=False)
 
    def __unicode__(self):
        return self.title
 
    def save(self, **kwargs):
        if not self.id:
            self.created = datetime.now() # Edit created timestamp only if it's new entry
        self.updated = datetime.now()
        super(Article,self).save()

You can make created and updated fields editable in admin by removing editable=False from DateTimeField and adding a bit of code in save method to modify created and update timestamps as per your wish instead of current timings. (Hint: for new entry check created and updated are None and for existing entry(while editing), check the updated and created values with existing values)

Below is the Djangocon 2008 presentation where auto_now and auto_now_add are discussed (34:00)


2 thoughts on “Django Timestamp without using auto_now and auto_now_add

  1. There is another way:

    from datetime import datetime

    class MyClass(models.Model):
    def __init__(self):
    models.Model.__init__(self)
    if not self.created:
    self.init = datetime.now()

    id = models.AutoField(primary_key=True)
    created = models.DateTimeField(null=True)

  2. I would really like to talk about, nice internet site. Internet marketing not sure if perhaps many experts have addressed, when utilizing Firefox I will by no means find the overall webpage so that you can heap without having relaxing a lot of situations. Could just be my own device.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>