#24163 - Tests altering of OneToOneField to ForeignKey
(self)
| 1847 | |
| 1848 | @skipUnlessDBFeature("supports_foreign_keys", "can_introspect_foreign_keys") |
| 1849 | def test_alter_o2o_to_fk(self): |
| 1850 | """ |
| 1851 | #24163 - Tests altering of OneToOneField to ForeignKey |
| 1852 | """ |
| 1853 | # Create the table |
| 1854 | with connection.schema_editor() as editor: |
| 1855 | editor.create_model(Author) |
| 1856 | editor.create_model(BookWithO2O) |
| 1857 | # Ensure the field is right to begin with |
| 1858 | columns = self.column_classes(BookWithO2O) |
| 1859 | self.assertEqual( |
| 1860 | columns["author_id"][0], |
| 1861 | connection.features.introspected_field_types["BigIntegerField"], |
| 1862 | ) |
| 1863 | # Ensure the field is unique |
| 1864 | author = Author.objects.create(name="Joe") |
| 1865 | BookWithO2O.objects.create( |
| 1866 | author=author, title="Django 1", pub_date=datetime.datetime.now() |
| 1867 | ) |
| 1868 | with self.assertRaises(IntegrityError): |
| 1869 | BookWithO2O.objects.create( |
| 1870 | author=author, title="Django 2", pub_date=datetime.datetime.now() |
| 1871 | ) |
| 1872 | BookWithO2O.objects.all().delete() |
| 1873 | self.assertForeignKeyExists(BookWithO2O, "author_id", "schema_author") |
| 1874 | # Alter the OneToOneField to ForeignKey |
| 1875 | old_field = BookWithO2O._meta.get_field("author") |
| 1876 | new_field = ForeignKey(Author, CASCADE) |
| 1877 | new_field.set_attributes_from_name("author") |
| 1878 | with connection.schema_editor() as editor: |
| 1879 | editor.alter_field(BookWithO2O, old_field, new_field, strict=True) |
| 1880 | columns = self.column_classes(Book) |
| 1881 | self.assertEqual( |
| 1882 | columns["author_id"][0], |
| 1883 | connection.features.introspected_field_types["BigIntegerField"], |
| 1884 | ) |
| 1885 | # Ensure the field is not unique anymore |
| 1886 | Book.objects.create( |
| 1887 | author=author, title="Django 1", pub_date=datetime.datetime.now() |
| 1888 | ) |
| 1889 | Book.objects.create( |
| 1890 | author=author, title="Django 2", pub_date=datetime.datetime.now() |
| 1891 | ) |
| 1892 | self.assertForeignKeyExists(Book, "author_id", "schema_author") |
| 1893 | |
| 1894 | @skipUnlessDBFeature("supports_foreign_keys", "can_introspect_foreign_keys") |
| 1895 | def test_alter_fk_to_o2o(self): |
nothing calls this directly
no test coverage detected