Opened 2 years ago

Closed 2 years ago

#19454 closed Cleanup/optimization (duplicate)

Wrong date in the fields DateTimeField with auto_now_add

Reported by: fizista Owned by: nobody
Component: Database layer (models, ORM) Version: 1.4
Severity: Normal Keywords: auto_now_add auto_now DateTimeField
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Example:

class ExampleModel(models.Model):
    date_update = models.DateTimeField(auto_now=True)
    date_create = models.DateTimeField(auto_now_add=True)

Let's create an object:

> obj = ExampleModel()
> print obj.date_create # Should not be here already set the date of creation of the object?
None
> obj.save()
> assert obj.date_update == obj.date_create
*** AssertionError: 

Conclusion:
auto_now_add - Creates a field with unspecified date

The documentation tells us:

DateField.auto_now_add
Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it's not just a default value that you can override.

If we mean by creating an object:

> new_object = ExampleModel() # then we should get
> print new_object.date_create # datetime.datetime object with creation date

If, however, the creation of an object is the time to save it to the database, then you should get something like this:

> obj = ExampleModel()
> print obj.date_create # in this case it is correct
None
> obj.save()
> assert obj.date_update == obj.date_create # == True

Change History (1)

comment:1 Changed 2 years ago by aaugustin

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to duplicate
  • Status changed from new to closed

This is already tracked by #16745.

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