Hi I was wondering if anyone knows of the most efficient way to find out if a column has a foreignKey relationship or not.
I had a similar problem. Actually I didn't have the table object, but the table name, and similarly the column name. Here is my solution:
from sqlalchemy.schema import MetaData
from sqlalchemy import create_engine
engine = create_engine( URL )
meta = MetaData()
meta.reflect(bind=engine)
def is_foreign_key(table_name, col_name):
return col_name in [e.target_fullname for e in meta.tables[table_name].foreign_keys]
NOTE:
meta.tables[table_name].foreign_keys == Table.__table__.foreign_keys
The ForeignKey
objects associated with an individual Column
object are available in the foreign_keys collection of that column.
foreign_keys_set = StudentIntendCourse.__table__.c.studentID.foreign_keys
You can check if this set is non empty
All columns have the attribute 'foreign_keys', that is a set, but it is empty for all column that are not ForeignKey, so a simple test can give you the correct answer. In your example:
def is_foreign_key(column):
return True if column.foreign_keys else False
print(is_foreign_key(StudentIntendCourse.studentID))
If you want to have list of all ForeignKey:
from sqlalchemy.inspection import inspect
foreign_keys_list = [c.key for c in inspect(StudentIntendCourse) if getattr(StudentIntendCourse, c.key).foreign_keys]
I strongly suggest to use inspection, instead, directly access the nested structures of SQLAlchemy.