Polymorphic relationships in sqlalchemy

85 Views Asked by At

I need to make relationships between 3 models that currently look like this:

class Chapter(Base):
    __tablename__ = "chapters"
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String)
    start = Column(DateTime, index=True)
    duration = Column(Interval)
    meeting_id = mapped_column(ForeignKey("meetings.id"))       #|
    meeting = relationship("Meeting", back_populates="chapters")#|
    upload_id = mapped_column(ForeignKey("uploads.id"))         #|
    upload = relationship("Upload", back_populates="chapters")  #| Change to polymorphic

class Meeting(Base):
    __tablename__ = "meetings"
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String)
    description = Column(Text)
    start = Column(DateTime, index=True)
    duration = Column(Interval)
    chapters = relationship("Chapter", back_populates="meeting")

class Upload(Base):
    __tablename__ = "uploads"
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String)
    description = Column(Text)
    duration = Column(Interval)
    path = Column(String)
    filename = Column(String)
    chapters = relationship("Chapter", back_populates="upload")

Instead of separate meeting_id and upload_id columns on Chapter, i would like to have an Enum field with the possible "chapterable" types, so that i can call some_chapter.chapterable and have it return an instance of Meeting or Upload, depending on the chapterable_type.

The current solution works, but is not ideal.

I have done some googling, and found many examples of using __mapper_args__, but there were many different versions. I'm hoping someone can give some tips on how this should be done right. I started using sqlalchemy last week so this is pretty new to me :D

0

There are 0 best solutions below