summaryrefslogtreecommitdiff
path: root/django
diff options
context:
space:
mode:
authorDiego Guimarães <diegobr.sistemas@gmail.com>2014-09-08 19:38:07 +0200
committerTim Graham <timograham@gmail.com>2014-11-27 19:42:30 -0500
commitf39b0421b406b411c3bcb58e8aa415d885fea505 (patch)
treea98fcdb8b484682feb7f02c3ce52ac06686aefaf /django
parentabf87333a163717308927ad1f230efe45d622c69 (diff)
Fixed #23338 -- Added warning when unique=True on ForeigKey
Thanks Jonathan Lindén for the initial patch, and Tim Graham and Gabe Jackson for the suggestions.
Diffstat (limited to 'django')
-rw-r--r--django/contrib/auth/tests/test_management.py1
-rw-r--r--django/db/models/fields/related.py15
2 files changed, 16 insertions, 0 deletions
diff --git a/django/contrib/auth/tests/test_management.py b/django/contrib/auth/tests/test_management.py
index 20f6c58f05..72d61a0919 100644
--- a/django/contrib/auth/tests/test_management.py
+++ b/django/contrib/auth/tests/test_management.py
@@ -153,6 +153,7 @@ class ChangepasswordManagementCommandTestCase(TestCase):
@skipIfCustomUser
+@override_settings(SILENCED_SYSTEM_CHECKS=['fields.W342']) # ForeignKey(unique=True)
class CreatesuperuserManagementCommandTestCase(TestCase):
def test_basic_usage(self):
diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
index ea88d19a17..04189ad097 100644
--- a/django/db/models/fields/related.py
+++ b/django/db/models/fields/related.py
@@ -1710,6 +1710,7 @@ class ForeignKey(ForeignObject):
def check(self, **kwargs):
errors = super(ForeignKey, self).check(**kwargs)
errors.extend(self._check_on_delete())
+ errors.extend(self._check_unique())
return errors
def _check_on_delete(self):
@@ -1735,6 +1736,16 @@ class ForeignKey(ForeignObject):
else:
return []
+ def _check_unique(self, **kwargs):
+ return [
+ checks.Warning(
+ 'Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.',
+ hint='ForeignKey(unique=True) is usually better served by a OneToOneField.',
+ obj=self,
+ id='fields.W342',
+ )
+ ] if self.unique else []
+
def deconstruct(self):
name, path, args, kwargs = super(ForeignKey, self).deconstruct()
del kwargs['to_fields']
@@ -1891,6 +1902,10 @@ class OneToOneField(ForeignKey):
else:
setattr(instance, self.attname, data)
+ def _check_unique(self, **kwargs):
+ # override ForeignKey since check isn't applicable here
+ return []
+
def create_many_to_many_intermediary_model(field, klass):
from django.db import models