簡體   English   中英

SQLAlchemy ORM 檢查列是否為foreign_key

[英]SQLAlchemy ORM check if column is a foreign_key

嗨,我想知道是否有人知道找出列是否具有外鍵關系的最有效方法。

class StudentIntendCourse(DeclarativeBase):
    __tablename__ = 'studentIntendCourse'
    id = Column(Integer, primary_key=True)
    studentID = Column('studentID',Integer,ForeignKey('student.id'))
    courseID = Column('courseID',Integer,ForeignKey('course.id'))
    course = relationship("Course",backref="studentIntendedCourses")

我想知道 is_foreign_key(StudentIntendCourse.studentID) 是否?

與單個Column對象關聯的ForeignKey對象在該列的foreign_keys集合中可用。

foreign_keys_set = StudentIntendCourse.__table__.c.studentID.foreign_keys

您可以檢查此集合是否為非空

我有一個類似的問題。 實際上我沒有表對象,而是表名,以及類似的列名。 這是我的解決方案:

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]

筆記:

meta.tables[table_name].foreign_keys == Table.__table__.foreign_keys

所有列都有屬性“foreign_keys”,這是一個集合,但對於所有不是 ForeignKey 的列,它都是空的,所以一個簡單的測試就可以給你正確的答案。 在你的例子中:

def is_foreign_key(column):
    return True if column.foreign_keys else False

print(is_foreign_key(StudentIntendCourse.studentID))

如果您想擁有所有外鍵的列表:

from sqlalchemy.inspection import inspect

foreign_keys_list = [c.key for c in inspect(StudentIntendCourse) if getattr(StudentIntendCourse, c.key).foreign_keys]

我強烈建議使用檢查,而不是直接訪問 SQLAlchemy 的嵌套結構。

我通過使用檢查的sqlalchemy.orm.Mapper.relationships解決了這個問題

from sqlalchemy.inspection import inspect

foreign_keys = [c.key for c in inspect(model).relationships]

希望這對任何人都有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM