On Fri, Feb 22, 2013 at 1:31 AM, Jonathan Vanasco <jonat...@findmeon.com> wrote:
> basd on a bunch of error messages, this example works...
>
>     criteria = ( ('male',35),('female','35) )
>     query = session.query( model.Useraccount )
>     ands = []
>     for set_ in criteria :
>                 ands.append(\
>                         sqlalchemy.sql.expression.and_(\
>                                 model.Useraccoun.gender == set_[0] ,
>                                 model.Useraccoun.age == set_[1] ,
>                         )
>                 )
>         query = query.filter(\
>                 sqlalchemy.sql.expression.or_( *ands )
>         )
>         results= query.all()
>
> this seems really awkward though.  is there a better way to build up a
> set of dynamic "or" criteria ?
>

It doesn't look too awkward to me - what sort of API would you prefer?

Note that and_ and or_ are available in the top-level "sqlalchemy"
namespace. Also, backslashes aren't necessary on the end of lines when
you're inside brackets, so your example could actually look like this:

    import sqlalchemy as sa

    criteria = (('male', 35), ('female', 35))
    Useraccount = model.Useraccount
    query = session.query(Useraccount)
    ands = []
    for gender, age in criteria:
        ands.append(
            sa.and_(
                Useraccount.gender == gender,
                Useraccount.age == age,
                )
        )
    query = query.filter(sa.or_(*ands))
    results= query.all()

It's entirely subjective, but I find that easier to read.

You can also use "&" and "|" but I think you have to be a little
careful with operator precedence. You can probably write this:

        ands.append((Useraccount.gender == gender) & (Useraccount.age == age))

Simon

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to