From 6d1f5769455ad8e1384087b92aa5839c3540d9ba Mon Sep 17 00:00:00 2001 From: Oscar Esgalha Date: Fri, 27 Apr 2018 14:32:10 -0300 Subject: [PATCH] Fixed #29367 -- Fixed model state on objects with a primary key created with QuerySet.bulk_create(). --- django/db/models/query.py | 3 +++ tests/bulk_create/tests.py | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/django/db/models/query.py b/django/db/models/query.py index 8d4c2d083c..1ef20d01d9 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -457,6 +457,9 @@ class QuerySet: objs_with_pk, objs_without_pk = partition(lambda o: o.pk is None, objs) if objs_with_pk: self._batched_insert(objs_with_pk, fields, batch_size) + for obj_with_pk in objs_with_pk: + obj_with_pk._state.adding = False + obj_with_pk._state.db = self.db if objs_without_pk: fields = [f for f in fields if not isinstance(f, AutoField)] ids = self._batched_insert(objs_without_pk, fields, batch_size) diff --git a/tests/bulk_create/tests.py b/tests/bulk_create/tests.py index b12ddcaeca..2b3e65594f 100644 --- a/tests/bulk_create/tests.py +++ b/tests/bulk_create/tests.py @@ -252,3 +252,12 @@ class BulkCreateTests(TestCase): # Objects save via bulk_create() and save() should have equal state. self.assertEqual(country_nl._state.adding, country_be._state.adding) self.assertEqual(country_nl._state.db, country_be._state.db) + + def test_set_state_with_pk_specified(self): + state_ca = State(two_letter_code='CA') + state_ny = State(two_letter_code='NY') + State.objects.bulk_create([state_ca]) + state_ny.save() + # Objects save via bulk_create() and save() should have equal state. + self.assertEqual(state_ca._state.adding, state_ny._state.adding) + self.assertEqual(state_ca._state.db, state_ny._state.db)