Opened 19 years ago

Closed 17 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

Description

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.

Model:

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

Behavior:

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

Attachments (1)

django-core-meta-init.py.diff (816 bytes ) - added by eric@… 19 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 by Andreas, 19 years ago

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 tasks_tasks.id = %s" % str(self.id)) 
        self.create_date = cursor.fetchone()[0]

comment:2 by richie@…, 19 years ago

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 by Maniac <Maniac@…>, 19 years ago

It also prevents an object with auto_now_add from being saved twice because it tries to set create_date to :

t.save()
t.title='Another title'
t.save()

gives:

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

by eric@…, 19 years ago

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

comment:4 by eric@…, 19 years ago

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 by Chris Beaven, 18 years ago

Has patch: set
Triage Stage: UnreviewedAccepted

comment:6 by Chris Beaven, 17 years ago

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