Last active
June 3, 2020 00:28
-
-
Save tnibert/a034d1ac1f23952048d09c6def7700fe to your computer and use it in GitHub Desktop.
Get all foreign keys from SQLAlchemy schema
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy.ext.declarative import declarative_base | |
""" | |
This gist demonstrates ways to retrieve foreign keys in an SQLAlchemy database schema. | |
""" | |
Base = declarative_base() | |
metadata = Base.metadata | |
# then you must populate schema | |
# one method: sqlacodegen postgresql://user:pass@localhost/dbname --outfile schema.py | |
# once you have a schema, | |
# you can do the following to retrieve all foreign keys for a single table by column: | |
def identify_foreign_keys(tablename): | |
""" | |
:param tablename: string | |
""" | |
retlist = [] | |
for c in metadata.tables[tablename].columns: | |
# if no foreign keys, c.foreign_keys will be an empty set | |
for fk in c.foreign_keys: | |
retlist.append({'column': str(c), 'foreign_linked_column': str(fk.column)}) | |
return retlist | |
# Table objects also have a foreign_keys member, for example: | |
for namestr, table in metadata.tables.items(): | |
if len(table.foreign_keys) > 0: | |
print("{} - {}".format(namestr, table.foreign_keys)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment