Opened 4 years ago

Closed 4 years ago

#17654 closed Bug (invalid)

auto_now_add=True column creates IntegrityError if model is saved by specifying an id

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

Description

To reproduce, create a new model which has an auto_now_add=True field and specify the id. When calling save() the IntegrityError is raised:

# Order has this field: created_at = models.DateTimeField(auto_now_add=True, null=False)
o = models.Order(id=1, name="abc")
o.save()
IntegrityError: null value in column "created_at" violates not-null constraint

Change History (3)

comment:1 Changed 4 years ago by anonymous

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

Here is the code section, correctly formatted:

# Order has this field: created_at = models.DateTimeField?(auto_now_add=True, null=False) 
o = models.Order(id=1, name="abc") 
o.save() 
IntegrityError: null value in column "created_at" violates not-null constraint

comment:2 Changed 4 years ago by anonymous

Also, I should add that the Order with id=1 already existed in the db (with a valid created_at date) at the time it was saved again. So it's the second save() that causes the problem.

comment:3 Changed 4 years ago by akaariai

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

There isn't any bug if this happens only when there is already an object with the same PK in the database. Because now you are not doing an add, you are doing an update. I think it works as specified, although I can see that this might be a bit confusing. The key here is that the id field's value identifies the object, so from Django's point of view you are really saving the same object to the DB, not adding a new one.

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