简体   繁体   中英

SQLalchemy select all with optional attributes

with SQLalchemy I query my database. I'm able to select all multiple rows / objects with something like this:

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

However, I want to build a function that checks if there any constraints given and if so incorporates these. So I was thinking along the following lines:

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...

As you can see this gets really ugly when the amount of attributes increase. What is the pythonic way to do this?

Query objects are chainable, from docs :

Query is produced in terms of a given Session, using the query() method:

q = session.query(SomeMappedClass)

So you can write something like this:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM