Optimize builiding query

Use `reduce` with generators instead of nested for loops with extra variables and `if`s.

Usage of:

    if or_query:
        or_query = or_query | q
    else:
        or_query = q

and

    if query:
        query = query & or_query
    else:
        query = or_query

is kind of overkill. I think that the solutions with `reduce` is more elegant.