I am not understanding why I have "None" as the foreign key constraint name. #1029
Replies: 3 comments 10 replies
-
foreign key constraints can be created in the database without passing a name. in this case, PostgreSQL will choose a name for each one automatically. The issue comes when you want to write new migrations that wants to drop these constraints; when that happens, you need to supply the names. If PostgreSQL generated those names, you'd need to look in your database and manually write in those names for these constraints; additionally, Alembic might have trouble detecting that these PostgreSQL-named constraints match the ones you have in your model, since they don't have the same name. So to solve all that we have the naming convention practice. To use that with Flask, you'd need to set up this naming convention in the main Flask metadata object as described at https://stackoverflow.com/questions/29153930/changing-constraint-naming-conventions-in-flask-sqlalchemy/29153957#29153957 . if the naming convention is set up, then when Alembic generates foreign key directives and other constraint directives you will see these names in the code it generates, such as : def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"test",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("name", sa.Text(), nullable=True),
sa.PrimaryKeyConstraint("id", name=op.f("pk_test")),
)
op.create_table(
"o",
sa.Column("test_id", sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(
["test_id"], ["test.id"], name=op.f("fk_o_test_id_test")
),
sa.PrimaryKeyConstraint("test_id", name=op.f("pk_o")),
) above you can see the PrimaryKeyConstraints and the ForeignKeyConstraint have a "name" present. that's the naming convention thing at work. If you dont have a naming convention then you'd see None as you are seeing in those alter statements. |
Beta Was this translation helpful? Give feedback.
-
I guess I am not understanding what file I am looking for. |
Beta Was this translation helpful? Give feedback.
-
I still get this problem. When the table is first created, everything is okay, and it follows naming convention. However, if I add foreign key later to the model, alembic generates it with |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I read online that I don't need a name for my foreign key constraints so I'm not sure why it is showing up as migration change.
Migration file:
env.py file:
models.py source table:
Is there a way I can manually add a foreign key constraint name if I really need to? It doesn't make sense if I don't need one then why is this happening?
Beta Was this translation helpful? Give feedback.
All reactions