接受表和列名的泛型函数,返回与给定过滤值匹配的所有主键值

1 投票
2 回答
588 浏览
提问于 2025-04-15 22:32

我在代码中有很多这样的函数:

def get_M_status(S): 
    M_id = marital.select(marital.c.marital_status_description == S).execute().fetchone()
    if M_id == None:
        print "Warning: No Marital id found for %s Marital status to Single" % S
        M_id = marital.select(marital.c.marital_status_description == "Single").execute().fetchone()       
    return M_id[0]

我在想有没有办法写一个通用的函数,这样我就可以传入相关的值,比如:表名、主键列、过滤列和过滤值。

谢谢!

2 个回答

1

这个表对象有一个叫做 primary_key 的属性,它包含了组成主键的列。你只需要选择这个属性,然后加上条件语句,就完成了:

def get_pks_by_col(tbl, col_name, col_value):
    s = select(tbl.primary_key.columns).where(tbl.columns[col_name] == col_value)
    return s.execute().fetchall()

根据你的具体情况进行修改。(len(tbl.primary_key) == 1 是保证的,需要传入连接以便执行等等。)

1

如果主键只有一列,你可以这样做:

getattr(table.c, pkey_col_name) == S

这就像是 marital.c.marital_status_description == S 的“通用”版本。

所以,可以这样做(请注意:这个还没测试过):

def get_row(table, col_name, val, default=None):
    col = getattr(table.c, col_name)
    row = table.select(col == S).execute().fetchone()
    if row == None:
        print "Warning: No row found for %s in %s; using %s" % (val, table, default)
        row = table.select(col == default).execute().fetchone()       
    return row[0]

如果你有映射的类,这会更简单;你可以这样做:

record = session.query(Marital).get(key)

这里的 Marital 是表 marital 的映射类,session 是一个 SQLAlchemy 的会话,key 是一个按顺序排列的主键列的元组。如果这个主键在表中存在,record 就会是找到的那一行;否则,它会是 None

撰写回答