diff --git a/piccolo/apps/migrations/auto/migration_manager.py b/piccolo/apps/migrations/auto/migration_manager.py index 53f4a3a7c..ce085783f 100644 --- a/piccolo/apps/migrations/auto/migration_manager.py +++ b/piccolo/apps/migrations/auto/migration_manager.py @@ -546,11 +546,12 @@ async def _run_alter_columns(self, backwards: bool = False): constraint_name = await get_fk_constraint_name( column=fk_column ) - await self._run_query( - _Table.alter().drop_constraint( - constraint_name=constraint_name + if constraint_name: + await self._run_query( + _Table.alter().drop_constraint( + constraint_name=constraint_name + ) ) - ) # Then add a new foreign key constraint await self._run_query( diff --git a/piccolo/query/constraints.py b/piccolo/query/constraints.py index 7f6d1f565..a5859c100 100644 --- a/piccolo/query/constraints.py +++ b/piccolo/query/constraints.py @@ -1,10 +1,11 @@ from dataclasses import dataclass +from typing import Optional from piccolo.columns import ForeignKey from piccolo.columns.base import OnDelete, OnUpdate -async def get_fk_constraint_name(column: ForeignKey) -> str: +async def get_fk_constraint_name(column: ForeignKey) -> Optional[str]: """ Checks what the foreign key constraint is called in the database. """ @@ -40,7 +41,10 @@ async def get_fk_constraint_name(column: ForeignKey) -> str: column_name, ) - return constraints[0]["fk_constraint_name"] + # if we change the column type from a non-FK column to + # an FK column, the previous column type has no FK constraints + # and we skip this to allow the migration to continue + return constraints[0]["fk_constraint_name"] if constraints else None @dataclass