From 0fb51ec5a0ab445aa178761f80f7415ac8098998 Mon Sep 17 00:00:00 2001 From: Jacob Walls Date: Tue, 7 Jan 2025 06:28:57 -0500 Subject: [PATCH] Fixed #36068 -- Raised ValueError when providing a composite PK field to bulk_create() update_fields. --- django/db/models/query.py | 2 +- tests/composite_pk/test_create.py | 17 ++++++++++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/django/db/models/query.py b/django/db/models/query.py index 1a44523374..39cae056ae 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -728,7 +728,7 @@ class QuerySet(AltersData): "bulk_create() can only be used with concrete fields in " "update_fields." ) - if any(f.primary_key for f in update_fields): + if any(f in self.model._meta.pk_fields for f in update_fields): raise ValueError( "bulk_create() cannot be used with primary keys in " "update_fields." diff --git a/tests/composite_pk/test_create.py b/tests/composite_pk/test_create.py index 7c9925b946..a007952f66 100644 --- a/tests/composite_pk/test_create.py +++ b/tests/composite_pk/test_create.py @@ -1,4 +1,4 @@ -from django.test import TestCase +from django.test import TestCase, skipUnlessDBFeature from .models import Tenant, User @@ -77,6 +77,21 @@ class CompositePKCreateTests(TestCase): self.assertEqual(obj_3.pk, (obj_3.tenant_id, obj_3.id)) self.assertEqual(obj_3.email, "user8214@example.com") + @skipUnlessDBFeature( + "supports_update_conflicts", + "supports_update_conflicts_with_target", + ) + def test_bulk_create_user_with_pk_field_in_update_fields(self): + objs = [User(tenant=self.tenant, id=8291, email="user8291@example.com")] + msg = "bulk_create() cannot be used with primary keys in update_fields." + with self.assertRaisesMessage(ValueError, msg): + User.objects.bulk_create( + objs, + update_conflicts=True, + update_fields=["tenant_id"], + unique_fields=["id", "tenant_id"], + ) + def test_get_or_create_user(self): test_cases = ( {