SQLAlchemy ORM check if column is a foreign_key

后端 未结 3 852
逝去的感伤
逝去的感伤 2021-01-14 04:05

Hi I was wondering if anyone knows of the most efficient way to find out if a column has a foreignKey relationship or not.



        
3条回答
  •  执笔经年
    2021-01-14 04:21

    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
    

提交回复
热议问题