From e917ea6bec45d7f789ca96a13be15df9521963e1 Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Wed, 14 Feb 2018 09:57:31 -0500 Subject: [PATCH] Fixed #29126 -- Doc'd the behavior of QuerySet.update_or_create() with manually specified pks. --- docs/ref/models/querysets.txt | 4 ++++ tests/get_or_create/tests.py | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt index 2d6702beeb..72d6accd2e 100644 --- a/docs/ref/models/querysets.txt +++ b/docs/ref/models/querysets.txt @@ -1988,6 +1988,10 @@ As described above in :meth:`get_or_create`, this method is prone to a race-condition which can result in multiple rows being inserted simultaneously if uniqueness is not enforced at the database level. +Like :meth:`get_or_create` and :meth:`create`, if you're using manually +specified primary keys and an object needs to be created but the key already +exists in the database, an :exc:`~django.db.IntegrityError` is raised. + ``bulk_create()`` ~~~~~~~~~~~~~~~~~ diff --git a/tests/get_or_create/tests.py b/tests/get_or_create/tests.py index 60e1ef23f2..1aed318608 100644 --- a/tests/get_or_create/tests.py +++ b/tests/get_or_create/tests.py @@ -444,6 +444,19 @@ class UpdateOrCreateTests(TestCase): self.assertEqual(obj.last_name, 'NotHarrison') +class UpdateOrCreateTestsWithManualPKs(TestCase): + + def test_create_with_duplicate_primary_key(self): + """ + If an existing primary key is specified with different values for other + fields, then IntegrityError is raised and data isn't updated. + """ + ManualPrimaryKeyTest.objects.create(id=1, data='Original') + with self.assertRaises(IntegrityError): + ManualPrimaryKeyTest.objects.update_or_create(id=1, data='Different') + self.assertEqual(ManualPrimaryKeyTest.objects.get(id=1).data, 'Original') + + class UpdateOrCreateTransactionTests(TransactionTestCase): available_apps = ['get_or_create']