Opened 10 years ago

Closed 8 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
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: UI/UX:

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

comment:2 Changed 10 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 10 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.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

Changed 9 years ago by eric@…

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

comment:4 Changed 9 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 9 years ago by SmileyChris

  • Has patch set
  • Triage Stage changed from Unreviewed to Accepted

comment:6 Changed 8 years ago by SmileyChris

  • Resolution set to fixed
  • Status changed from new to closed

auto_now and auto_now_add have been removed altogether

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