On Thu, 2006-05-18 at 21:02 +0100, Christopher Arndt wrote:
> Oleg Broytmann wrote:
> > On Thu, May 18, 2006 at 05:51:47PM +0100, Christopher Arndt wrote:
> > 
> >>class MySelectResult:
> >>    def __nonzero__(self):
> >>        return self.count() > 0
> >>
> >>SQLObject.SelectResultsClass.__bases__ += (MySelectResult,)
> >>
> >>class Person(SQLObject):
> >>    name = StringCol(alternateID=True, length=20)
> >>    org = StringCol(length=100)
> >>
> >>if __name__ == '__main__':
> >>    Person.createTable()
> >>    u1 = Person(name="joe", org="doe.com")
> >>    u2 = Person(name="alice", org="foo.com")
> >>    u3 = Person(name="bob", org="foo.com")
> >>
> >>    pl = Person.select(Person.q.org == 'foo.com')
> >>    if pl:
> >>        for p in pl:
> >>            print p.name
> >>    else:
> >>        print "No records found."
> > 
> > 
> >    You ran two query. Is it really neccessary? Why not just
> 
> Ok, this probably not the best example. But sometimes you just want to
> access the first (or the last) item of the result set.
> 
> res = Person.select(...)
> if res:
>     return res[0].someAttr
> else:
>     return some_default

If you're only getting 1 record the call to count() may actually be more
costly than selecting the record, so you should still avoid it.  You
could probably do this a few ways, but catching the IndexError seems the
cleanest to me:

try:
    res = Person.select()[0]
except IndexError:
    return default
else:
    return res.someAttr

It might save people confusion if bool(SelectResults) Just Worked(TM),
but I think the extra database trip will always be unnecessary.  

-- 
Matt Good <[EMAIL PROTECTED]>



-------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642
_______________________________________________
sqlobject-discuss mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/sqlobject-discuss

Reply via email to