From babd4126853e48594b61e8db71a83d7bdd929b9c Mon Sep 17 00:00:00 2001 From: Abhijeet Viswa Date: Wed, 26 Feb 2020 23:19:05 +0530 Subject: [PATCH] Fixed #29129 -- Skipped UPDATE when adding a model instance with inherited primary key that has a default. --- django/db/models/base.py | 4 ++-- tests/basic/models.py | 4 ++++ tests/basic/tests.py | 10 ++++++++-- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/django/db/models/base.py b/django/db/models/base.py index b47f4c287de..2555d8c1b54 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -855,8 +855,8 @@ class Model(metaclass=ModelBase): not raw and not force_insert and self._state.adding and - self._meta.pk.default and - self._meta.pk.default is not NOT_PROVIDED + meta.pk.default and + meta.pk.default is not NOT_PROVIDED ): force_insert = True # If possible, try an UPDATE. If that doesn't update anything, do an INSERT. diff --git a/tests/basic/models.py b/tests/basic/models.py index 7b2b1aee54f..6dcdfa90c0c 100644 --- a/tests/basic/models.py +++ b/tests/basic/models.py @@ -46,3 +46,7 @@ class SelfRef(models.Model): class PrimaryKeyWithDefault(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4) + + +class ChildPrimaryKeyWithDefault(PrimaryKeyWithDefault): + pass diff --git a/tests/basic/tests.py b/tests/basic/tests.py index e1869584005..22093f5a56e 100644 --- a/tests/basic/tests.py +++ b/tests/basic/tests.py @@ -12,8 +12,8 @@ from django.test import ( from django.utils.translation import gettext_lazy from .models import ( - Article, ArticleSelectOnSave, FeaturedArticle, PrimaryKeyWithDefault, - SelfRef, + Article, ArticleSelectOnSave, ChildPrimaryKeyWithDefault, FeaturedArticle, + PrimaryKeyWithDefault, SelfRef, ) @@ -139,6 +139,12 @@ class ModelInstanceCreationTests(TestCase): with self.assertNumQueries(1): PrimaryKeyWithDefault().save() + def test_save_parent_primary_with_default(self): + # An UPDATE attempt is skipped when an inherited primary key has + # default. + with self.assertNumQueries(2): + ChildPrimaryKeyWithDefault().save() + class ModelTest(TestCase): def test_objects_attribute_is_only_available_on_the_class_itself(self):