python - SQLAlchemy 在泛型函数中使用 ORM 选择多个列
问题描述
我正在使用以下课程:
class PostGreSQL:
def __init__(self, db:str, table:Table):
self.db = db
self.table = table
engine = create_engine(DATABASE_URL+db, pool_size=3, max_overflow=0)
metadata.create_all(engine)
self.conn = engine.connect()
def __read(self,col:str="",cond:str=""):
if cond:
cmd = select(self.table.c[col] if col!="" else self.table).where(text(cond))
else:
cmd = select(self.table.c[col] if col!="" else self.table)
return self.conn.execute(cmd)
要仅选择一列的值,我曾经使用以下方法调用该函数:
pgs = PostGreSQL(my_db, Users)
age = pgs._read(col="age", cond="name = 'John Doe'").fetchone()
现在我想返回多个列,假设特定用户的参数“年龄”和“爱好”。
如果我用以下方法调用相同的函数:
response = pgs._read(col="age, hobby", cond="name = 'John Doe'").fetchone()
我得到错误:
KeyError: 'age,hobby'
这似乎表明table.c[]
只接受一个列键。
我的问题是:我应该如何修改函数以返回两列?
该函数应该是通用的和可扩展的,以接受列键的任何组合。
任何建议都非常感谢。
解决方案
如果您想为__read()
您维护相同的界面,可以使用以下代码:
from sqlalchemy.sql import select
from sqlalchemy.sql.expression import column, text
def __read(col:str="",cond:str=""):
col = [column(x) for x in col.split(", ")] if col!="" else []
cmd = select(col) if col!=[] else select(["*"])
cmd = cmd.select_from(self.table)
if cond:
cmd = cmd.where(text(cond))
return self.conn.execute(cmd)
如果可以改接口,可以直接传列列表,去掉列表推导
推荐阅读
- vb.net - 将包含名称的文本文件加载到文本框
- checkbox - Xamarin 窗体为 CheckBox 控件创建 Clicked 事件
- selenium - 无法从登录弹出页面传递到 Selenium 中的密码弹出页面
- unity3d - Unity输入字段未在更改时设置值
- android - 避免将 null 作为视图根传递(在 AlertDialog 中膨胀布局时)
- javascript - Github 高严重性安全漏洞:带有 Node.js 应用程序的 GHSA-7fhm-mqm4-2wp7
- css - 如何保持具有动态内容的元素的圆形形状?
- html - HTML a 无法更改大小或移动
- wordpress - Unable to create directory wp-content/uploads/2020/03. Is its parent directory writable by the server?
- dictionary - 使用带有 PageView 的表单会用每个页面 Flutter 覆盖以前的表单数据