簡體   English   中英

SQLalchemy選擇所有帶有可選屬性

[英]SQLalchemy select all with optional attributes

與SQLalchemy我查詢我的數據庫。 我可以選擇所有具有以下內容的行/對象:

def selectAllObjects():
    objects = session.query(Object).all()

但是,我想構建一個函數來檢查是否有給定的約束,以及是否包含這些約束。 所以我在考慮以下方面:

def selectAllObjects(attribute1="default",attribute2="default"):
    if attribute1 != "default" and attribute2 != default:
        objects = session.query(Object).filter_by(attribute1=attribute1,
                  attribute2=attribute2).all()
    elif attribute1 != "default":
        objects = session.query(Object).filter_by(attribute1=attribute1).all()
    ...etc, etc...

如您所見,當屬性數量增加時,這變得非常難看。 pythonic的方法是什么?

Query對象是可鏈接的,來自docs

使用query()方法根據給定的會話產生查詢:

q = session.query(SomeMappedClass)

所以你可以這樣寫:

def selectAllObjects(attribute1="default", attribute2="default"):
    query = session.query(Object)
    if attribute1 != "default" and attribute2 != "default":
        query = query.filter_by(
            attribute1=attribute1,
            attribute2=attribute2,
        )
    elif attribute1 != "default":
        query = query.filter_by(attribute1=attribute1)
    return query.all()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM