2010-05-10 24 views
1

我有一個是通過散落出來的代碼泛型函數接受一個表和字段名,並返回所有的主鍵值,鑑於

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] 

我在想,如果功能看起來像這樣的一個過濾器值相匹配他們是寫一個通用的功能,我可以通過相關值,即一個辦法:表名主鍵字段篩選列和過濾器值

歡呼

+0

您的縮進不正確。這使得破譯意圖變得困難。 – 2010-05-10 08:06:54

+0

對此表示抱歉 – 2010-05-10 08:11:45

回答

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是SQL鍊金術會話,key是鍵列的元組(按順序)。如果表中存在密鑰,則找到record行;否則將是None

1

表對象具有包含組成主鍵的列的primary_key屬性。選擇該項,只需添加where子句即可完成:

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有保證,需要通過連接執行等)

相關問題