mirror of
https://github.com/django/django.git
synced 2025-10-31 09:41:08 +00:00
Fixed #24447 -- Made migrations add FK constraints for existing columns
When altering from e.g. an IntegerField to a ForeignKey, Django didn't
add a constraint.
Backport of f4f0060fea from master
This commit is contained in:
committed by
Markus Holtermann
parent
7f2d60996c
commit
283b630d63
@@ -11,7 +11,7 @@ from .fields import CustomManyToManyField, InheritedManyToManyField
|
||||
from .models import (Author, AuthorWithDefaultHeight, AuthorWithM2M, Book, BookWithLongName,
|
||||
BookWithSlug, BookWithM2M, Tag, TagIndexed, TagM2MTest, TagUniqueRename,
|
||||
UniqueTest, Thing, TagThrough, BookWithM2MThrough, AuthorTag, AuthorWithM2MThrough,
|
||||
AuthorWithEvenLongerName, BookWeak, Note, BookWithO2O)
|
||||
AuthorWithEvenLongerName, BookWeak, Note, BookWithO2O, BookWithoutFK)
|
||||
|
||||
|
||||
class SchemaTests(TransactionTestCase):
|
||||
@@ -29,7 +29,7 @@ class SchemaTests(TransactionTestCase):
|
||||
Author, AuthorWithM2M, Book, BookWithLongName, BookWithSlug,
|
||||
BookWithM2M, Tag, TagIndexed, TagM2MTest, TagUniqueRename, UniqueTest,
|
||||
Thing, TagThrough, BookWithM2MThrough, AuthorWithEvenLongerName,
|
||||
BookWeak, BookWithO2O,
|
||||
BookWeak, BookWithO2O, BookWithoutFK,
|
||||
]
|
||||
|
||||
# Utility functions
|
||||
@@ -536,6 +536,38 @@ class SchemaTests(TransactionTestCase):
|
||||
else:
|
||||
self.fail("No FK constraint for author_id found")
|
||||
|
||||
@unittest.skipUnless(connection.features.supports_foreign_keys, "No FK support")
|
||||
def test_alter_to_fk(self):
|
||||
"""
|
||||
#24447 - Tests adding a FK constraint for an existing column
|
||||
"""
|
||||
# Create the tables
|
||||
with connection.schema_editor() as editor:
|
||||
editor.create_model(Author)
|
||||
editor.create_model(BookWithoutFK)
|
||||
# Ensure no FK constraint exists
|
||||
constraints = self.get_constraints(BookWithoutFK._meta.db_table)
|
||||
for name, details in constraints.items():
|
||||
if details['foreign_key']:
|
||||
self.fail('Found an unexpected FK constraint to %s' % details['columns'])
|
||||
new_field = ForeignKey(Author)
|
||||
new_field.set_attributes_from_name("author")
|
||||
with connection.schema_editor() as editor:
|
||||
editor.alter_field(
|
||||
BookWithoutFK,
|
||||
BookWithoutFK._meta.get_field_by_name("author")[0],
|
||||
new_field,
|
||||
strict=True,
|
||||
)
|
||||
constraints = self.get_constraints(BookWithoutFK._meta.db_table)
|
||||
# Ensure FK constraint exists
|
||||
for name, details in constraints.items():
|
||||
if details['foreign_key'] and details['columns'] == ["author_id"]:
|
||||
self.assertEqual(details['foreign_key'], ('schema_author', 'id'))
|
||||
break
|
||||
else:
|
||||
self.fail("No FK constraint for author_id found")
|
||||
|
||||
@unittest.skipUnless(connection.features.supports_foreign_keys, "No FK support")
|
||||
def test_alter_o2o_to_fk(self):
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user