Django

Code

Ticket #555 (closed: fixed)

Opened 3 years ago

Last modified 1 year ago

DateTimeFields with auto_now and auto_now_add don't change in place

Reported by: Andreas Assigned to: adrian
Component: Core framework Version:
Keywords: Cc: eric@ericwalstad.com
Triage Stage: Accepted Has patch: 1
Needs documentation: 0 Needs tests: 0
Patch needs improvement: 0

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

django-core-meta-init.py.diff (0.8 kB) - added by eric@ericwalstad.com on 02/06/06 22:14:30.
Patch to update date/time fields with whatever was saved into the database.

Change History

09/25/05 08:36:28 changed 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]

10/29/05 17:53:04 changed by richie@entrian.com

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!

11/16/05 12:08:55 changed by Maniac <Maniac@SoftwareManiacs.Org>

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

02/06/06 22:14:30 changed by eric@ericwalstad.com

  • attachment django-core-meta-init.py.diff added.

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

02/06/06 22:16:22 changed by eric@ericwalstad.com

  • cc set to eric@ericwalstad.com.

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.

01/17/07 22:47:59 changed by SmileyChris

  • has_patch set to 1.
  • stage changed from Unreviewed to Accepted.

05/22/07 17:29:47 changed by SmileyChris

  • status changed from new to closed.
  • resolution set to fixed.

auto_now and auto_now_add have been removed altogether


Add/Change #555 (DateTimeFields with auto_now and auto_now_add don't change in place)




Change Properties
Action