'SQLAlchemy create relationship between 2 different files

I am trying to create a many to many relationship between to tables in SQLAlchemy, that are in different files (in python, in VSCode). I created a common base in a base_class.py file and determined an association table.

I have the following code:

  • In the edge.py file:
from sqlalchemy.schema import Table
from sqlalchemy import Column, String, Integer, Float, ForeignKey
from sqlalchemy.orm import relationship
from base_class import Base

association_cs_compressor = Table(
    "cs_compressor_association",
    Base.metadata,
    Column("compressor_station_id", ForeignKey("CompressorStationModel._id")),
    Column("compressor_id", ForeignKey("CompressorModel._id")))

class EdgeModel:
    id = Column(String, nullable=False, primary_key=True)
    from = Column(String, nullable=False)
    ...

class CompressorStationModel(EdgeModel, Base):
    __tablename__ = "Compressor Station"

    compressor_relationship = relationship(
        "CompressorModel",
        secondary=association_cs_compressor,
        backref="Compressor Station")

    drag_factor_out = Column(Integer)
    diameter_in = Column(Integer)
    ...
  • In the compressor.py file I have the following code:
from sqlalchemy import Column, String, Integer, Float, ForeignKey
from sqlalchemy.orm import relationship
from base_class import Base

class CompressorModel(Base):
    __tablename__ = "Compressors"

    cs_relationship = relationship(
        "CompressorStationModel",
        secondary=association_cs_compressor,
        backref="Compressors",
    )

    compressor_id = Column(String, nullable=False, primary_key=True)
    compressor_station_id = Column(String, nullable=False)
    drive_id = Column(String, nullable=False)
    ...

When I try to setup the databases and create objects I get the following error:

"NoForeignKeysError: Could not determine join condition between parent/child tables on relationship CompressorStationModel.compressor_relationship - there are no foreign keys linking these tables via secondary table 'cs_compressor_association'. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify 'primaryjoin' and 'secondaryjoin' expressions."

I don't really understand the SQLAlchemy documentation, does anyone understand where the problem is coming from? The CompressorStation must be able to find the corresponding compressors that it has with an id.

Thanks a lot in advance!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source