On Jun 10, 2011, at 6:15 PM, Darren Yin wrote:
> I want to construct a clause by anding the previous clause with new clauses,
> and I was wondering if there was a standard way to initialize an empty
> clause. First, here's some code that illustrates the general idea of what I'm
> trying to do:
>
> clause = True
> if cond1:
> clause = and_(clause, cond1_clause)
> if cond2:
> clause = and_(clause, cond2_clause)
>
> and then I execute the select(cols, clause) query.
There's no slick way to do that right now, we tend to keep it simple:
if clause is None:
clause = myclause
else:
clause = clause & myclause
if you're doing a selection of ifs,
clauses = []
if cond1:
clauses.append(cond1)
if cond2:
clauses.append(cond2)
result = and_(*clauses)
> Is there some better value to initialize clause to? From experimentation,
> None as an initial value also does what I want, but initially setting clause
> to None then might lead to confusion since it's False in Python and (roughly,
> correct me if I'm wrong) True in SQLAlchemy.
and_() of any scalar value just spits the value back. So and_(None) is just
None, but also isn't useful as a "builder" the way you're trying to do it,
though I feel like im misunderstanding since you mention this same thing
below....
>
> Also, is there a good value to initialize clause to in order for code of the
> following sort to work? Or is this a bad practice?
>
> clause = some_init_value
> if cond1:
> clause &= cond1_clause
> if cond2:
> clause &= cond2_clause
>
> Because the and_ and or_ methods special case the single argument case (just
> passing them through), the simplest thing I've found to work is the
> and_(True, True) construct. But that's exceedingly hacky imo.
>
> Thanks in advance!
> --Darren
>
> --
> You received this message because you are subscribed to the Google Groups
> "sqlalchemy" group.
> To post to this group, send email to sqlalchemy@googlegroups.com.
> To unsubscribe from this group, send email to
> sqlalchemy+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/sqlalchemy?hl=en.
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en.