Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
Dropping foreign keys in Alembic downgrade?

So I have created a number of tables in my database using an Alembic migration, each has an index and one or two foreign keys.

My upgrade method works fine, executes and creates the tables.

My downgrade method fails, after I drop my indexes and then drop my tables. I believe I also have to drop my foreign keys first? However I can't figure out how to drop foreign keys from the Alembic Documentation.

Downgrade method:

def downgrade():
    # Drop Indexes
    op.drop_index('ix_charge_id')
    op.drop_index('ix_statutory_provision_id')
    op.drop_index('ix_originating_authority_id')

    # Drop Tables
    op.drop_table('charge')
    op.drop_table('statutory_provision')
    op.drop_table('originating_authority')

Each of these three tables has a foreign key, so how do I go about dropping these first?

TYIA.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You just need to call drop constrain. So in your upgrade method you might have the following:

op.create_foreign_key(u'my_fkey', 'table1', 'table2', ['table2_id'], ['id'])

Then in your downgrade method you just need to have

op.drop_constraint(u'my_fkey', 'table1', type_='foreignkey')

One thing to watch for is that you assign a name when you create the foreign key, or known exactly the naming convention that will be used by the database. When you drop the constraint you need to specify the exact name being used.

One last thing which might help and save you time is to use the auto revision function of alembic. I find this saves a lot of the heavy lifting, and then I can just tweak the scripts if I need to.

alembic revision --autogenerate -m <message>

Check out http://alembic.zzzcomputing.com/en/latest/autogenerate.html for more information about the autogenerate, but it really is a time saver.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!