Commits

Anonymous committed a810258

[soc2009/model-validation] Fixed #12132: unneccessary unique_check for primary key when not adding model

Comments (0)

Files changed (3)

django/db/models/base.py

                 f = self._meta.get_field(field_name)
                 lookup_value = getattr(self, f.attname)
                 if f.null and lookup_value is None:
+                    # no value, skip the lookup
+                    continue
+                if f.primary_key and not getattr(self, '_adding', False):
+                    # no need to check for unique primary key when editting 
                     continue
                 lookup_kwargs[str(field_name)] = lookup_value
 

tests/modeltests/validation/test_unique.py

 import unittest
 
-from models import CustomPKModel, UniqueTogetherModel, UniqueFieldsModel, UniqueForDateModel
+from django.conf import settings
+from django.db import connection
+
+from models import CustomPKModel, UniqueTogetherModel, UniqueFieldsModel, UniqueForDateModel, ModelToValidate
 
 class GetUniqueCheckTests(unittest.TestCase):
     def test_unique_fields_get_collected(self):
         )
 
 
+class PerformUniqueChecksTest(unittest.TestCase):
+    def setUp(self):
+        self._old_debug, settings.DEBUG = settings.DEBUG, True
+        super(PerformUniqueChecksTest, self).setUp()
 
+    def tearDown(self):
+        settings.DEBUG = self._old_debug
+        super(PerformUniqueChecksTest, self).tearDown()
+
+    def test_primary_key_unique_check_performed_when_adding(self):
+        "Check#12132"
+        l = len(connection.queries)
+        mtv = ModelToValidate(number=10, name='Some Name')
+        setattr(mtv, '_adding', True)
+        mtv.clean()
+        self.assertEqual(l+1, len(connection.queries))
+
+    def test_primary_key_unique_check_not_performed_when_not_adding(self):
+        "Check#12132"
+        l = len(connection.queries)
+        mtv = ModelToValidate(number=10, name='Some Name')
+        mtv.clean()
+        self.assertEqual(l, len(connection.queries))

tests/modeltests/validation/tests.py

 from models import *
 
 from validators import TestModelsWithValidators
-from test_unique import GetUniqueCheckTests
+from test_unique import GetUniqueCheckTests, PerformUniqueChecksTest
 from test_custom_messages import CustomMessagesTest
 
 class BaseModelValidationTests(ValidationTestCase):