SQLAlchemy ORM check if column is a foreign_key

后端 未结 3 853
逝去的感伤
逝去的感伤 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
    
    0 讨论(0)
  • 2021-01-14 04:28

    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

    0 讨论(0)
  • 2021-01-14 04:32

    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.

    0 讨论(0)
提交回复
热议问题