Skip to content

Instantly share code, notes, and snippets.

@grant-humphries
Last active February 19, 2016 23:54
Show Gist options
  • Save grant-humphries/782aca5c500c6a924f43 to your computer and use it in GitHub Desktop.
Save grant-humphries/782aca5c500c6a924f43 to your computer and use it in GitHub Desktop.
pg_url = 'postgres://{user}:{pw}@{host}/{db}'
engine = create_engine(pg_url)
metadata = MetaData(bind=ops.engine)
metadata.reflect(schema='tbl_schema', only=['tbl_name'])
fk_column = metadata.tables['tbl_schema.tbl_name'].columns['tbl_column']
fk = ForeignKey(fk_column)
# list of columns that should have the foreign key
fk_list = [...]
# list of column objects that are not yet associated with a table
for col in columns:
if col.name in fk_list:
col.foreign_keys.add(fk)
print col.foreign_keys
# output shows that foreign key has been added
table = Table(
table_name,
metadata,
*columns
)
table.create()
print table.foreign_keys
# output shows table has no foreign keys
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment