当前位置: 首页 > 工具软件 > flask-graphql > 使用案例 >

python mysql l链式查询_使用python flask sqlacalchemy orm在PostgreSQL中联接查询

夹谷辰沛
2023-12-01

如果您喜欢编写常规的SQL语句,那么为什么不使用SQLAlchemy来完成这项工作呢?你不需要使用像这样的链式方法

join

,

filter_by

等来查询数据库。

为了回答这个问题,我需要对你的

models

文件。我假设是这样的:

from flask_sqlalchemy import SQLAlchemy

import datetime

db = SQLAlchemy()

class BaseModel(db.Model):

"""Base data model for all objects"""

# more code here

class x(BaseModel, db.Model):

# more table setup code here

class y(BaseModel, db.Model):

# more table setup code here

如果是这种情况,那么您可以执行简单的旧参数化SQL语句:

from flask import Flask

from models import db

import json

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'your_database_connection_string'

db.init_app(app)

result = db.session.execute("select * from x inner join y on x.name = :name", {"name":"xyz"})

# If no rows were returned in the result, return an empty list

if result.returns_rows == False:

response = []

# Convert the response to a plain list of dicts

else:

response = [dict(row.items()) for row in result]

# Output the query result as JSON

print(json.dumps(response))

我发现用sqlAlchemy在flash中运行SQL查询的方法要比使用原始文章中尝试的所有不同方法链接更容易理解和理解。

 类似资料: