Opened 20 years ago
Closed 19 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)
Change History (7)
comment:1 by , 20 years ago
comment:2 by , 20 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 , 20 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 , 20 years ago
| Attachment: | django-core-meta-init.py.diff added |
|---|
Patch to update date/time fields with whatever was saved into the database.
comment:4 by , 20 years ago
| Cc: | 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 , 19 years ago
| Has patch: | set |
|---|---|
| Triage Stage: | Unreviewed → Accepted |
comment:6 by , 19 years ago
| Resolution: | → fixed |
|---|---|
| Status: | new → closed |
auto_now and auto_now_add have been removed altogether
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]