首页 > 解决方案 > SQLAlchemy:找不到主连接条件的任何相关外键列

问题描述

我在我的 postgres CLI 中建立了两个表(test2_table:id、name、age、professional、city、country)。第二个引用了我的第一个表的 ID,并且有一个名为工资的列。当我运行语法时,一切都很好。

SELECT name, age, profession, city, country, wage FROM test2_table JOIN salary ON salary.test2_id = test2_table.id; 

这行得通 - 打印了一张工资表供我查看。

我唯一的问题是当我对我的 SQLAlchemy 数据库类尝试同样的事情时。当我尝试将课程一起加入时,出现错误:

sqlalchemy.exc.ArgumentError: Could not locate any relevant foreign key columns for primary join condition 'test2_table.id = salary.id' on relationship Salary.wages.
Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or are annotated in the join condition with the foreign() annotation.

我的数据库类:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class Test_db_02(Base):
    __tablename__ = 'test2_table'
    id = Column('id', Integer, primary_key=True)
    name = Column('name', String(40))
    age = Column('age', Integer)
    profession = Column('profession', String(60))
    city = Column('city', String(60))
    country = Column('country', String(40))

class Salary(Base):
    __tablename__ = 'salary'
    id = Column('id', Integer, primary_key=True)
    wage = Column('wage', String(20))
    test2_id = Column('test2_id', Integer, ForeignKey('test2_table.id'))

    wages = relationship("Test_db_02", backref="salary", primaryjoin="Test_db_02.id == Salary.id")

我有一个简单的报告页面,提示用户从下拉选项选择器中进行选择。在我尝试将这两个表加入之前,我的查询运行良好,现在在我尝试加入之后我得到了错误。对于此示例,报告 @app 已按比例缩小。

报告@app.route

Session = sessionmaker(bind=engine)
session = Session()

@app.route('/reports', methods=['GET', 'POST'])
if request.method == 'GET':
    return render_template('reports.html')
else:
    if request.form.get("report_options") == "all_db":
        db_entry = session.query(Test_db_02).order_by(Test_db_02.id)
        db_entry = db_entry.all()
        return render_template('reports.html', db_entry=db_entry)
    elif request.form.get("report_options") == "name":
        db_entry = session.query(Test_db_02).order_by(Test_db_02.id)
        data_name = db_entry.all()
        return render_template('reports.html', data_name=data_name)
    elif request.form.get("report_options") == "media_prof":
        db_entry = session.query(Test_db_02).join(test2_table.salary)
        media_prof = db_entry.all()
        return render_template('reports.html', media_prof=media_prof)

老实说,我已经阅读了有关关系、连接和外键的 sqlalchemy 文档(并观看了一些 YouTube 教程),但它似乎仍然有点令人困惑..

对我来说主要的挑战是能够将两张桌子连接在一起。完成此操作后,我将尝试通过设置烧瓶/神器来遍历它们。

标签: pythonsqlalchemy

解决方案


你的primaryjoin条件Salary.wages是错误的。据推测,是一个自动增量主键列,并且由于您对 的值Salary.id没有ForeignKey约束值 ,因此您不太可能像您所做的那样将该列包含在连接条件中:Salary.idTest_db_02.id

primaryjoin="Test_db_02.id == Salary.id"

您更有可能希望通过Salary.test2_id属性关联两个模型,因为您ForeignKey对该列有约束:

primaryjoin="Test_db_02.id == Salary.test2_id"

推荐阅读