x和y之间的NoForeignKeysError

时间:2018-07-09 03:07:52

标签: python sqlalchemy

Base = declarative_base()


class Database:
    def __init__(self):
        engine = create_engine('mysql+pymysql://...')
        self.session = sessionmaker(bind=engine)()
        Base.metadata.create_all(engine)
        print(engine.connect().execute(
              'Select * From Customer LEFT JOIN CustomerContact On Customer.ID = CustomerContact.CustomerID')
              .fetchall())


class Customer(Base):
    __tablename__ = 'Customer'
    ID = Column(String, primary_key=True)
    Name = Column(String)
    contacts = relationship('CustomerContact')


class CustomerContact(Base):
    __tablename__ = 'CustomerContact'
    ID = Column(Integer, primary_key=True)
    CustomerID = (String, ForeignKey('Customer.ID'))
    Name = Column(String)
    Title = Column(String, default='')
    ContactInfo = Column(String, default='')
    Notes = Column(String, default='')


if __name__ == '__main__':
    db = Database()
    s = db.session
    s.query(Customer)

运行这两行:

session.query(Customer).all()  
session.query(Customer).join(CustomerContact).all()  

结果

sqlalchemy.exc.NoForeignKeysError: Can't find any foreign key relationships 
 between 'Customer' and 'CustomerContact'. 

而且似乎查询任何与这两个类有关的东西都会吐出那些错误

我已经检查了拼写错误和其他线程,并运行了原始的sql语句以查看其他地方是否存在问题,但效果很好

我在http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#one-to-many上遵循示例 并无法为我的生活弄清楚到底是什么问题

如果有人可以帮助我指出正确的方向,以进一步解决此问题或问题所在,那就太好了。

2 个答案:

答案 0 :(得分:0)

您应该在选择项本身中引用外键

代替:

session.query(Customer).join(CustomerContact).all()

尝试:

session.query(Customer).join(CustomerContact, CustomerContact.CustomerID==Customer.contacts).all()

答案 1 :(得分:0)

忘记在上调用Column()

CustomerID = (String, ForeignKey('Customer.ID'))

谢谢IljaEverilä!