Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy ORM check if column is a foreign_key

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

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")

I would like to find out if is_foreign_key(StudentIntendCourse.studentID)?

like image 574
Gooseware Avatar asked Jul 27 '26 03:07

Gooseware


1 Answers

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

like image 191
r-m-n Avatar answered Jul 29 '26 17:07

r-m-n