Opened 2 years ago

Closed 2 years ago

#34225 closed Bug (invalid)

bulk_create() raises IntegrityError when another constraint exists on set of fields.

Reported by: Victor J. Fuente Owned by: nobody
Component: Database layer (models, ORM) Version: 4.1
Severity: Normal Keywords: #bulk_create
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

bulk_create on 4.1 perform a bulk_update when a unique constraint fails.

But on this example, when the constraint fails, an integrity Error occur and no update is in place

class Test(models.Model):

    field1 = models.IntegerField(null=True, blank=True)
    field2 = models.IntegerField(null=True, blank=True)
    count = models.IntegerField(null=True, blank=True)

    class Meta:

        db_table = "test"

        constraints = [
            models.UniqueConstraint(
                models.functions.Coalesce("field1", 0),
                models.functions.Coalesce("field2", 0),
                name="test_coal_unique",
            ),
            models.UniqueConstraint(
                "field1",
                "field2",
                name="test_unique",
            ),
        ]


t1 = Test(field1=1,field2=None,count=1)
t2 = Test(field1=1,field2=None,count=2)

Test.objects.bulk_create([t1, t2], ignore_conflicts=False, update_conflicts=True, unique_fields=['field1','field2'], update_fields = ['count'])

django.db.utils.IntegrityError: duplicate key value violates unique constraint "test_coal_unique"
DETAIL:  Key (COALESCE(field1, 0), COALESCE(field2, 0))=(1, 0) already exists.

Change History (1)

comment:1 by Mariusz Felisiak, 2 years ago

Resolution: invalid
Status: newclosed
Summary: django 4.1.x - bulk_create - django.db.utils.IntegrityError: duplicate key value violates unique constraintbulk_create() raises IntegrityError when another constraint exists on set of fields.

Thanks for the report, however Django is not at fault. NULL values don't violate unique constraints so set of unique fields passed to the ON CONFLICT(...) is not violated i.e. the test_unique constraint. The second constraint (test_coal_unique) is violated but it's not taken into account by ON CONFLICT statement. If you're having trouble understanding how this statement is evaluated by your database, see TicketClosingReasons/UseSupportChannels for ways to get help.

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