Opened 15 years ago

Closed 13 years ago

#555 closed defect (fixed)

DateTimeFields with auto_now and auto_now_add don't change in place

Reported by: Andreas Owned by: Adrian Holovaty
Component: Core (Other) Version:
Severity: normal Keywords:
Cc: eric@… Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


When saving an instance of a model that includes a DateTimeField with auto_now or auto_now_add, the automatically inserted date will not show up until the instance is reloaded from the db.


class Task(meta.Model):
    create_date = meta.DateTimeField("Created on", auto_now_add=True)
    title = meta.CharField(maxlength=200)


>>> from django.models.tasks import *
>>> t = Task(title="task")
>>> print 'presave', t.create_date
>>> # Now t has a create_date
>>> print 'postsave', t.create_date
>>> # But it shows only in the database, not in the instance t.

Attachments (1) (816 bytes) - added by eric@… 14 years ago.
Patch to update date/time fields with whatever was saved into the database.

Download all attachments as: .zip

Change History (7)

comment:1 Changed 15 years ago by Andreas

Ugly workaround:

    def _post_save(self):
        from django.core.db import db 
        cursor = db.cursor() 
        cursor.execute("SELECT tasks_tasks.create_date FROM tasks_tasks WHERE = %s" % str( 
        self.create_date = cursor.fetchone()[0]

comment:2 Changed 15 years ago by richie@…

I've just been bitten by this, and it took a *long* time to figure out what was going on. Andreas, many thanks for the workaround - ugly or not, it does the job!

comment:3 Changed 15 years ago by Maniac <Maniac@…>

It also prevents an object with auto_now_add from being saved twice because it tries to set create_date to :
t.title='Another title'


psycopg.ProgrammingError: ERROR: invalid input syntax for type timestamp with time zone: ""

UPDATE "tasks_tasks" SET "id"=1,"create_date"=,"title"='Another title' WHERE "id"=1

Changed 14 years ago by eric@…

Patch to update date/time fields with whatever was saved into the database.

comment:4 Changed 14 years ago by eric@…

Cc: eric@… added

I just added a patch that updates the object's date-like fields after saving to the database with the same values that were saved to the database.

comment:5 Changed 13 years ago by Chris Beaven

Has patch: set
Triage Stage: UnreviewedAccepted

comment:6 Changed 13 years ago by Chris Beaven

Resolution: fixed
Status: newclosed

auto_now and auto_now_add have been removed altogether

Note: See TracTickets for help on using tickets.
Back to Top