Opened 3 years ago

Closed 3 years ago

#33512 closed Bug (duplicate)

Creating a child instance with a parent containing DateTimeField(auto_add_now=True) raises IntegrityError.

Reported by: Eriks K Owned by: nobody
Component: Database layer (models, ORM) Version: 4.0
Severity: Normal Keywords: auto_add_now
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Mariusz Felisiak)

Description:
When creating Model object which inherits from other Model which has DateTimeField with auto_add_now=True and passing parent_ptr_id value, then Django tries to update base Model by setting the auto_now_add field to NUL (although the field is null=False)

Expected result:
ChildModel instance created with a link to ParentModel.

Code examples:
models.py

class ParentModel(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)


class ChildModel(ParentModel):
    some_field = models.CharField(max_length=12)

manage.py shell

from app.models import ParentModel, ChildModel
parent_object = ParentModel.objects.create()  # OK
ChildModel.objects.create()  # OK
ChildModel.objects.create(parentmodel_ptr=parent_object)  # IntegrityError

Actual result:
Django tries to update ParentModel's created with NULL

UPDATE "app_parentmodel" SET "created" = NULL, "modified" = ? WHERE "app_parentmodel"."id" = ?

And raises

django.db.utils.IntegrityError: NOT NULL constraint failed: app_parentmodel.created

Noticed in Django 2.2, reproduced in 3.2 and 4.0. with both Postgres and SQlite database backends.
Demo project on GitHub to reproduce bug.

Change History (1)

comment:1 by Mariusz Felisiak, 3 years ago

Description: modified (diff)
Resolution: duplicate
Status: newclosed
Summary: DateTimeField auto_add_now is NUL when creating child model object referencing parent model's objectCreating a child instance with a parent containing DateTimeField(auto_add_now=True) raises IntegrityError.

Thanks for the report! It looks like a different scenario for the same issue as described in #24539.

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