Skip to main content
 首页 » 编程设计

python之使用 sqlalchemy 查询连接表

2024年11月01日18mengfanrong

我有两个表,一个是信息表,另一个是工资表。我已经在我的 postgres CLI 和我的 flask 应用程序中成功地将这两个表连接在一起,但是在尝试查询 sqlalchemy 中的数据时遇到了问题。

我已经在我的 psql CLI 上尝试了我的查询并且工作正常!

SELECT date, name, profession, wage FROM test2_table JOIN salary ON salary.test2_id = test2_table.id WHERE profession = 'media'; 

我想我的主要问题是如何在 sqlalchemy 中执行此操作?

数据库类

class Test_db_02(Base): 
    __tablename__ = 'test2_table' 
    id = Column('id', Integer, primary_key=True) 
    date = Column('date', String(10)) 
    age = Column('age', Integer) 
    profession = Column('profession', String(60)) 
    city = Column('city', String(60)) 
    country = Column('country', String(60)) 
 
    def __init__(self, date, name, age, profession, city, country): 
        self.date = date 
        self.name = name 
        self.age = age 
        self.profession = profession 
        self.city = city 
        self.country = country 
 
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.test2_id") 

我在 python 中的查询:

@app.route('/reports', methods=['GET', 'POST']) 
def reports(): 
    if request.method == 'GET': 
        return render_template('reports.html') 
    else: 
        if request.form.get("report_options) == "media_prof": 
            db_entry = session.query(Test_db_02).join(Test_db_02.salary).filter(Test_db_02.profession=='media') 
        media_prof = db_entry.all() 
        return render_template('reports.html', media_prof=media_prof) 

reports.html 中的 jinja 模板:

{% if media_prof %} 
    <h2>Media Freelance Reports</h2> 
        <tr> 
            <th>ID</th> 
            <th>NAME</th> 
            <th>PROFESSION</th> 
            <th>SALARY</th> 
        </tr> 
    {% for d in media_prof %} 
        <tr> 
            <th>{{ d.id }}</th> 
            <th>{{ d.name }}</th> 
            <th>{{ d.profession }}</th> 
            <th>{{ d.salary }}</th> 
        </tr> 
    {% endfor %} 
{% endif %} 

幸运的是,它没有让我的网络应用程序崩溃,而是为每个媒体自由职业者生成薪水,我得到了: [<__main__.Salary object at 0x00CF11B0>]

我觉得这一定是我在 python 应用程序中查询数据库的方式或者我在 jinja 中调用变量的方式..

请您参考如下方法:

由于你是在ORM模式下使用SQLAlchemy(相对于core模式),查询的结果

db_entry = session.query(Test_db_02).join(Test_db_02.salary).filter(Test_db_02.profession=='media') 
media_prof = db_entry.all() 

是 Test_db_02 实例的列表,每个实例都有一个 .salary 属性,是一个 Salary 实例。所以当你在你的神社模板中使用它时很正常:

{% for d in media_prof %} 
    <tr> 
        <th>{{ d.id }}</th> 
        <th>{{ d.name }}</th> 
        <th>{{ d.profession }}</th> 
        <th>{{ d.salary }}</th> 
    </tr> 
{% endfor %} 

因为 d.salary 是一个实际的 Salary 实例列表(由于你的 backref 和你有一对多关系的事实),这意味着您有权访问每个薪水对象的属性,例如:.id 或 .wage 例如:

{% for d in media_prof %} 
    <tr> 
        <th>{{ d.id }}</th> 
        <th>{{ d.name }}</th> 
        <th>{{ d.profession }}</th> 
        {% for s in media_prof.salary %} 
            <th>{{ s.id }}</th> 
            <th>{{ s.wage }}</th> 
        {% endfor %} 
    </tr> 
{% endfor %} 

注意:考虑将你的反向引用“salary”重命名为“salaries”以使其更明确

编辑: 请注意,在模板之外排除故障更容易。从终端,我能够使用以下简化的案例获得正确的输出:

# Load an object in the db with 2 salaries attached to it 
t = Test_db_02(city='NY') 
s1 = Salary(wage='crazy rich', test2_id=t) 
s2 = Salary(wage='mega rich', test2_id=t) 
t.salaries = [s1, s2] 
 
session = Session() 
session.add(t) 
session.commit() 
 
# query & print 
session2 = Session() 
for test in session2.query(Test_db_02).all(): 
    print(test.id, test.city) 
    for salary in test.salaries: 
        print(salary.id, salary.wage) 

打印

1 NY 
1 crazy rich 
2 mega rich