Skip to content

Commit

Permalink
[soc2009/model-validation] Fixed #12132: unneccessary unique_check fo…
Browse files Browse the repository at this point in the history
…r primary key when not adding model

git-svn-id: http://code.djangoproject.com/svn/django/branches/soc2009/model-validation@11856 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information
honzakral committed Dec 13, 2009
1 parent 3b895d4 commit 695de8c
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
4 changes: 4 additions & 0 deletions django/db/models/base.py
Expand Up @@ -678,6 +678,10 @@ def _perform_unique_checks(self, unique_checks):
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

Expand Down
29 changes: 27 additions & 2 deletions tests/modeltests/validation/test_unique.py
@@ -1,6 +1,9 @@
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):
Expand All @@ -24,4 +27,26 @@ def test_unique_for_date_gets_picked_up(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))
2 changes: 1 addition & 1 deletion tests/modeltests/validation/tests.py
Expand Up @@ -5,7 +5,7 @@
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):
Expand Down

0 comments on commit 695de8c

Please sign in to comment.