mirror of
https://github.com/django/django.git
synced 2024-12-22 17:16:24 +00:00
Fixed #29358 -- Added a system check to prohibit models with more than one primary_key field.
This commit is contained in:
parent
98019df855
commit
816b8d9518
@ -1189,6 +1189,7 @@ class Model(metaclass=ModelBase):
|
||||
*cls._check_field_name_clashes(),
|
||||
*cls._check_model_name_db_lookup_clashes(),
|
||||
*cls._check_property_name_related_field_accessor_clashes(),
|
||||
*cls._check_single_primary_key(),
|
||||
)
|
||||
errors.extend(clash_errors)
|
||||
# If there are field name clashes, hide consequent column name
|
||||
@ -1436,6 +1437,19 @@ class Model(metaclass=ModelBase):
|
||||
)
|
||||
return errors
|
||||
|
||||
@classmethod
|
||||
def _check_single_primary_key(cls):
|
||||
errors = []
|
||||
if sum(1 for f in cls._meta.local_fields if f.primary_key) > 1:
|
||||
errors.append(
|
||||
checks.Error(
|
||||
"Model can not contain more than one 'primary_key' field.",
|
||||
obj=cls,
|
||||
id='models.E026',
|
||||
)
|
||||
)
|
||||
return errors
|
||||
|
||||
@classmethod
|
||||
def _check_index_together(cls):
|
||||
"""Check the value of "index_together" option."""
|
||||
|
@ -295,6 +295,7 @@ Models
|
||||
as it collides with the query lookup syntax.
|
||||
* **models.E025**: The property ``<property name>`` clashes with a related
|
||||
field accessor.
|
||||
* **models.E026**: Model can not contain more than one ``primary_key`` field.
|
||||
|
||||
Security
|
||||
--------
|
||||
|
@ -717,6 +717,19 @@ class OtherModelTests(SimpleTestCase):
|
||||
)
|
||||
])
|
||||
|
||||
def test_single_primary_key(self):
|
||||
class Model(models.Model):
|
||||
foo = models.IntegerField(primary_key=True)
|
||||
bar = models.IntegerField(primary_key=True)
|
||||
|
||||
self.assertEqual(Model.check(), [
|
||||
Error(
|
||||
"Model can not contain more than one 'primary_key' field.",
|
||||
obj=Model,
|
||||
id='models.E026',
|
||||
)
|
||||
])
|
||||
|
||||
@override_settings(TEST_SWAPPED_MODEL_BAD_VALUE='not-a-model')
|
||||
def test_swappable_missing_app_name(self):
|
||||
class Model(models.Model):
|
||||
|
Loading…
Reference in New Issue
Block a user