首页 > 解决方案 > 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[]只接受一个列键。

我的问题是:我应该如何修改函数以返回两列?

该函数应该是通用的和可扩展的,以接受列键的任何组合。

任何建议都非常感谢。

标签: pythonsqlalchemy

解决方案


如果您想为__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)

如果可以改接口,可以直接传列列表,去掉列表推导


推荐阅读