Dan Garthwaite
Dan Garthwaite

Reputation: 3526

How do I correct this sqlalchemy.exc.NoForeignKeysError?

Why do I get the TraceBack

sqlalchemy.exc.NoForeignKeysError: Could not determine join condition
between parent/child tables on relationship County.Legislators - 
there are no foreign keys linking these tables.

Ensure that referencing columns are associated with a
ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.

with the following models:

class County(Base):
    __tablename__ = 'tblCounty'
    CountyCode = Column('CountyCode', String, primary_key=True)
    Legislators = relationship('Legislators', backref='County', lazy='dynamic')

class Legislators(Base):
    __tablename__ = 'VLegislators'
    EmployeeNo = Column('EmployeeNo', String, primary_key=True)
    CountyCode = Column('CountyCode', String, ForeignKey('County.CountyCode'))

I'm trying to map a public facing MS SQL database provided by the State of New Hampshire. So no schema changes allowed.

Why does it complain about the lack of a ForeignKey relation when one is clearly defined in class Legislators?

Upvotes: 18

Views: 15472

Answers (1)

bav
bav

Reputation: 1623

AFAIK you should use tablename in ForeignKey:

CountyCode = Column('CountyCode', String, ForeignKey('tblCounty.CountyCode'))

Upvotes: 23

Related Questions