无法找到主要连接条件的外键列

时间:2016-02-23 06:21:27

标签: python sqlite sqlalchemy

我创建了以下数据库定义和测试数据:

from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.session import sessionmaker
Base = declarative_base()
# build dynamic table
cols = {'__tablename__': 'mytable', 'A': Column(String, primary_key=True), 'B': Column(Integer)}
table = type('mytable', (Base,), cols)
cols2 = {'__tablename__': 'mychild', 'A': Column(String, primary_key=True), 'Z': Column(Integer)}
cols2['parent_id'] = Column(String, ForeignKey('mytable.A'))
child_table = type('mychild', (Base,), cols2)
child_table.parent = relationship('mytable', backref='mytable', primaryjoin='mytable.A==mychild.A')
# initialize engine
from sqlalchemy import create_engine
engine = create_engine('sqlite:///', echo=True)
Base.metadata.create_all(engine)
# generate a toy dataframe and dump to sql
import pandas as pd
df = pd.DataFrame.from_dict({'B': {'row1': 1}})
df.to_sql('mytable', engine, if_exists='append', index_label='A')
Session = sessionmaker(bind=engine)
session = Session()
session.query(child_table)

这会导致错误

ArgumentError: Could not locate any relevant foreign key columns for primary join condition 'mytable."A" = mychild."A"' on relationship mychild.parent.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or are annotated in the join condition with the foreign() annotation.

一般来说,我对如何针对表格编写查询感到困惑。在这种情况下,我将如何执行select * from mytable或更有用的SELECT B,Z from mytable JOIN mychild using A之类的操作,这正是我通过此尝试实现的目标。

1 个答案:

答案 0 :(得分:4)

您需要在SQLAlchemy中在两个主要连接列之间声明一个外键约束,即使您实际上没有数据库中的

cols2 = {
    '__tablename__': 'mychild', 
    'A': Column(String, ForeignKey("mytable.A"), primary_key=True), 
    'Z': Column(Integer)
}