tags:

views:

81

answers:

2

How do I combine two columns and apply filter? For example, I want to search in both the "firstname" and "lastname" columns at the same time. Here is how I have been doing it if searching only one column:

query = meta.Session.query(User).filter(User.firstname.like(searchVar))
+1  A: 

You can use SQLAlchemy's or_ function to search in more than one column (the underscore is necessary to distinguish it from Python's own or).

Here's an example:

from sqlalchemy import or_
query = meta.Session.query(User).filter(or_(User.firstname.like(searchVar),
                                            User.lastname.like(searchVar)))
gclj5
You can use `|` operator instead of `or_`, like this - `(User.firstname.like(searchVar)) | (User.lastname.like(searchVar))`, however you should be careful with `|` precedence, without parenthesis it can produce VERY unexpected results when mixed with comparsion operators.
Daniel Kluev
A: 

You can simply call filter multiple times:

query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
                                 filter(User.lastname.like(searchVar2))
David Johnstone