[Zope] silly DTML question: "in" test

Dieter Maurer dieter at handshake.de
Sun Dec 2 13:57:29 EST 2007


Bill Seitz wrote at 2007-11-28 13:20 -0500:
>I want to see if a value (defined via url-arg) is in a list which is
>generated from an RDBMS query (field type=integer).
>
>The pseudo-code would be something like:
>
>if foo in (select foo_col from table where x=y)
>then z='t'
>else z='f'
>
>I tried putting the simple SELECT query into a zSql and then calling it like:
>
><dtml-call "REQUEST.set('foo_list',IfShowNextDoor())">
><dtml-if expr="foo in foo_list">
>	<dtml-call "REQUEST.set('z','t')">
><dtml-else>
>	<dtml-call "REQUEST.set('z','f')">
></dtml-if>
>
>But that doesn't work.

Off topic note: this is quite nasty and difficult to read code....

More helpful note:

  The result of a Z SQL Method call behaves like a sequence of
  rows.

  These rows are not strings; therefore "some_string == row" will
  fail (always return 'False') and correspondingly "some_string in
  sqlresult".

  The rows (they are in fact 'Record' instances) allow access
  to the fields either through a subscription ("row[0]", "row[1]" ...)
  or an attribute access ("row.field1", "row.field2", ...) syntax.

  Therefore, to get the list consisting of the first field
  of all rows, you may use

     [row[0] for row in IfShowNextDoor()]

  Your code above can then be replaced with:

    <dtml-call "REQUEST.set(
       'z',
       foo in [row[0] for row in IfShowNextDoor()] and 't' or 'f'
       )">

  which is already a lot more readable than your code.
  If possible, you should get rid of the "REQUEST.set"
  ("dtml-let" is more readable).


And, of course, the advice from someone else to let the datebase
perform the check for you it excellent: why do something inefficient
and clumsy yourself when someone else (database) can do it
more efficiently and more direct?



-- 
Dieter


More information about the Zope mailing list