#24447 - Tests adding a FK constraint for an existing column
(self)
| 1812 | |
| 1813 | @skipUnlessDBFeature("supports_foreign_keys") |
| 1814 | def test_alter_to_fk(self): |
| 1815 | """ |
| 1816 | #24447 - Tests adding a FK constraint for an existing column |
| 1817 | """ |
| 1818 | |
| 1819 | class LocalBook(Model): |
| 1820 | author = IntegerField() |
| 1821 | title = CharField(max_length=100, db_index=True) |
| 1822 | pub_date = DateTimeField() |
| 1823 | |
| 1824 | class Meta: |
| 1825 | app_label = "schema" |
| 1826 | apps = new_apps |
| 1827 | |
| 1828 | self.local_models = [LocalBook] |
| 1829 | |
| 1830 | # Create the tables |
| 1831 | with connection.schema_editor() as editor: |
| 1832 | editor.create_model(Author) |
| 1833 | editor.create_model(LocalBook) |
| 1834 | # Ensure no FK constraint exists |
| 1835 | constraints = self.get_constraints(LocalBook._meta.db_table) |
| 1836 | for details in constraints.values(): |
| 1837 | if details["foreign_key"]: |
| 1838 | self.fail( |
| 1839 | "Found an unexpected FK constraint to %s" % details["columns"] |
| 1840 | ) |
| 1841 | old_field = LocalBook._meta.get_field("author") |
| 1842 | new_field = ForeignKey(Author, CASCADE) |
| 1843 | new_field.set_attributes_from_name("author") |
| 1844 | with connection.schema_editor() as editor: |
| 1845 | editor.alter_field(LocalBook, old_field, new_field, strict=True) |
| 1846 | self.assertForeignKeyExists(LocalBook, "author_id", "schema_author") |
| 1847 | |
| 1848 | @skipUnlessDBFeature("supports_foreign_keys", "can_introspect_foreign_keys") |
| 1849 | def test_alter_o2o_to_fk(self): |
nothing calls this directly
no test coverage detected