SQLAlchemy select 在通用函数中使用 ORM 的多个列
SQLAlchemy select a plurality of colums using ORM in a generic function
我正在使用以下 class:
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)
到select我用来调用函数的只有一列的值:
pgs = PostGreSQL(my_db, Users)
age = pgs._read(col="age", cond="name = 'John Doe'").fetchone()
现在我想要 returned 多列,比方说特定用户的参数“年龄”和“爱好”。
如果我调用相同的函数:
response = pgs._read(col="age, hobby", cond="name = 'John Doe'").fetchone()
我收到错误:
KeyError: 'age,hobby'
这似乎表明 table.c[]
只接受一个列键。
我的问题是:我应该如何修改函数才能 return 两列?
该函数应该是通用的和可扩展的,以接受列键的任意组合。
非常感谢任何建议。
如果您想为 __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)
如果可以换个接口,可以直接传列list,去掉list comprehension
我正在使用以下 class:
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)
到select我用来调用函数的只有一列的值:
pgs = PostGreSQL(my_db, Users)
age = pgs._read(col="age", cond="name = 'John Doe'").fetchone()
现在我想要 returned 多列,比方说特定用户的参数“年龄”和“爱好”。
如果我调用相同的函数:
response = pgs._read(col="age, hobby", cond="name = 'John Doe'").fetchone()
我收到错误:
KeyError: 'age,hobby'
这似乎表明 table.c[]
只接受一个列键。
我的问题是:我应该如何修改函数才能 return 两列?
该函数应该是通用的和可扩展的,以接受列键的任意组合。
非常感谢任何建议。
如果您想为 __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)
如果可以换个接口,可以直接传列list,去掉list comprehension