Search code examples
pythonsqlalchemypyramid

SqlAlchemy can't determine join condition


I have 2 tables defined:

class TCableSet(Base):
    __tablename__ = 'tCableSet'

    ixCableSet = Column(Integer, primary_key=True)
    decCableSetOne = Column(Numeric(8, 2))
    decCableSetTwo = Column(Numeric(8, 2))
    decCableSetThree = Column(Numeric(8, 2))

class TStepVoltage(Base):
    __tablename__ = 'tStepVoltage'

    ixStepVoltage = Column(Integer, primary_key=True)
    ixSubReport = Column(Integer, ForeignKey('tSubReport.ixSubReport'), nullable=False)
    iVoltage = Column(Integer)
    ixPhaseA = Column(Integer, ForeignKey('tCableSet.ixCableSet'), nullable=False)
    ixPhaseB = Column(Integer, ForeignKey('tCableSet.ixCableSet'), nullable=False)
    ixPhaseC = Column(Integer, ForeignKey('tCableSet.ixCableSet'), nullable=False)

    sub_report = relationship('TSubReport',
                              backref=backref('step_voltage'))

I understand why I am getting this error but can't figure out a proper way (yet). When the table gets saved, I store the values in the tCableSet table and then use the id as a foreign key in my tStepVoltage table. The problem I have is when I go to retrieve the data, I want to be able to get the values(tCableSet row) along with the rest of my tStepVoltage table via a relationship, however I'm not sure how to go about this since I don't have a field in my tCableSet that can directly be linked via relationship to my tStepVoltage. I basically just needed the tCableSet for normalization


Solution

  • Since you have more than one foreign key that points to the same table, you have to tell SQLAlchemy which foreign key to use.

    For example:

    sub_report_a = relationship('TSubReport',
                                backref=backref('step_voltage'),
                                foreign_keys=[ixPhaseA])