#33649 closed Bug (invalid)
bulk_create() with ignore_conflicts=True and ForeignKey fails — at Version 1
Reported by: | Markus Friedrich | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 3.2 |
Severity: | Normal | Keywords: | bulk_create ForeignKey ignore_conflicts |
Cc: | Hannes Ljungberg | 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 )
Creating both objects of a many-to-one relation using bulk_create together with ignore_conflicts=True fails since Django >=3.2!
To enable many-to-one relations in bulk_create the "to_field" of the ForeignKey is defined via a UUIDField with a uuid.UUID4 default value.
Without the ignore_conflicts=True option of bulk_create it works well in all Django versions.
But if ignore_conflicts=True is needed since some of the objects using in the bulk_create may already be saved to the DB then it works only for Django < 3.2.
With Django >= 3.2 (including 4.0.4) it fails with:
ValueError: bulk_create() prohibited to prevent data loss due to unsaved related object 'reporter'
.
Find attached a test app which reproduces this issue with a minimal example, see
mysite/polls/models.py and mysite/polls/tests.py
Change History (2)
by , 3 years ago
Attachment: | mysite.zip added |
---|
comment:1 by , 3 years ago
Cc: | added |
---|---|
Component: | Uncategorized → Database layer (models, ORM) |
Description: | modified (diff) |
Resolution: | → invalid |
Status: | new → closed |
Summary: | bulk_create with ignore_conflicts=True and ForeignKey fails → bulk_create() with ignore_conflicts=True and ForeignKey fails |
Thanks for this report. This behavior was intentionally changed in 10f8b82d195caa3745ba37d9424893763f89653e to prevent possible data loss. Using
ignore_conflicts=True
tells the database to ignore failure to insert any rows that fail constraints such as duplicate unique values, but also disables setting the primary key on each model instance (as documented). Therefore areporter
instance doesn't have a primary key set. You need to attached already savedreporter
to thearticle
beforebulk_create()
.