|
22 | 22 | from django.test import (
|
23 | 23 | TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature,
|
24 | 24 | )
|
25 |
| -from django.test.utils import CaptureQueriesContext |
| 25 | +from django.test.utils import CaptureQueriesContext, isolate_apps |
26 | 26 | from django.utils import timezone
|
27 | 27 |
|
28 | 28 | from .fields import (
|
@@ -319,6 +319,37 @@ def test_fk_db_constraint(self):
|
319 | 319 | editor.alter_field(Author, new_field2, new_field, strict=True)
|
320 | 320 | self.assertForeignKeyNotExists(Author, 'tag_id', 'schema_tag')
|
321 | 321 |
|
| 322 | + @isolate_apps('schema') |
| 323 | + def test_no_db_constraint_added_during_primary_key_change(self): |
| 324 | + """ |
| 325 | + When a primary key that's pointed to by a ForeignKey with |
| 326 | + db_constraint=False is altered, a foreign key constraint isn't added. |
| 327 | + """ |
| 328 | + class Author(Model): |
| 329 | + class Meta: |
| 330 | + app_label = 'schema' |
| 331 | + |
| 332 | + class BookWeak(Model): |
| 333 | + author = ForeignKey(Author, CASCADE, db_constraint=False) |
| 334 | + |
| 335 | + class Meta: |
| 336 | + app_label = 'schema' |
| 337 | + |
| 338 | + with connection.schema_editor() as editor: |
| 339 | + editor.create_model(Author) |
| 340 | + editor.create_model(BookWeak) |
| 341 | + self.assertForeignKeyNotExists(BookWeak, 'author_id', 'schema_author') |
| 342 | + old_field = Author._meta.get_field('id') |
| 343 | + new_field = BigAutoField(primary_key=True) |
| 344 | + new_field.model = Author |
| 345 | + new_field.set_attributes_from_name('id') |
| 346 | + # @isolate_apps() and inner models are needed to have the model |
| 347 | + # relations populated, otherwise this doesn't act as a regression test. |
| 348 | + self.assertEqual(len(new_field.model._meta.related_objects), 1) |
| 349 | + with connection.schema_editor() as editor: |
| 350 | + editor.alter_field(Author, old_field, new_field, strict=True) |
| 351 | + self.assertForeignKeyNotExists(BookWeak, 'author_id', 'schema_author') |
| 352 | + |
322 | 353 | def _test_m2m_db_constraint(self, M2MFieldClass):
|
323 | 354 | class LocalAuthorWithM2M(Model):
|
324 | 355 | name = CharField(max_length=255)
|
|
0 commit comments