[Zope] ZSQL, Python Script, number of records

Shai Berger shai@aristocart.com
Mon, 06 Aug 2001 19:53:36 +0300


Hi Milos,

> To check whether a record exists I'm using this:
> 
> exist (ZSQL method):
> SELECT count(*) as I FROM ... WHERE ... ;
> 
> Python Script:
> for x in exist(m_id=m_id):
>   if x.i==0:
>      print "no data"
>   else:
>      print "there are some data"
> 
> This works... but it's strange to use "for" for it... is there a simpler 
> method? Just an "if", wthout "for"?
> 

if exist(m_id=m_id)[0][0]:
   ...

or 

if exist(m_id=m_id)[0].i:
   ...

The object returned by a ZSQL method is a list of rows.
The fields of the row can be accessed either by name (as
attributes of the row) or by number.


> I tried to adapt the "exist" ZSQL to show a column from the table:
> exist2 (ZSQL method):
> SELECT count(*) as I, fname FROM ... WHERE ... ;
> 
> It fails and it recommends to put "fname" into GROUP BY. So:
> exist3 (ZSQL method):
> SELECT count(*) as I, fname FROM ... WHERE ... GROUP BY fname;

What you seem to miss is that an SQL query always returns
a set of rows of uniform structure. That is, you cannot have
"a value and a list of values".

In your specific case, the situation is much simpler. The number
of items is the number of rows returned.

So,

exist4(ZSQL method):
SELECT fname FROM ... WHERE...;

In your python script:

names = exist4(m_id=m_id)
if(not names): # if there is no data, names is an empty list
  print "no data"
else:
  for name in names:
      ...

You can get the number of names as len(names).

HTH,
	Shai.