On Dec 12, 2007 6:20 AM, King Simon-NFHD78 <[EMAIL PROTECTED]> wrote:
>
> Felix Schwarz wrote:
> > Hi,
> >
> > after reading the docs [1] I thought that something like
> > session.query(User).filter(User.c.id > 3)[0]
> > should work even if the filter clause does not return any rows.
> >
> > But - compliant with Python's behavior - SQLAlchemy raises an
> > IndexError.
> > (...)
> >    File
> > "/usr/lib/python2.4/site-packages/sqlalchemy/orm/query.py",
> > line 577, in __getitem__
> >      return list(self[item:item+1])[0]
> > IndexError: list index out of range
> > I expected that [0] applied to query without results would
> > return None.
> >
> > Did I miss another possibility for LIMIT'ing queries (using
> > sqlalchemy.orm)?
> >
> > fs
> >
> > [1]
> > http://www.sqlalchemy.org/docs/04/ormtutorial.html#datamapping
> > _querying
>
> I think being matching Python's behaviour is definitely the right way to
> go. If you want to get None specifically for index [0], you can use the
> 'first' method on query.
>
> If you are happy get an empty list, you could use a slice and then call
> .all()

The issue is that [0] in Python superficially looks like [A:B] but is
in fact something different.
[A:B] was added to SQLAlchemy to represent .offset(A).limit(B-A).  [0]
came along for the ride but has incompatible semantics when the record
does not exist.  I guess I would favor None because
[N]'s closest equivalent is .fetchone() which does that, and if they
really wanted [] they should have done
[:1].

Raising IndexError is the native Python equivalent, but the whole
concept of operator overloading is that we do what makes sense for the
object.  A query is not a list.  If we define [N] as "skip N-1 records
and do .fetchone()", that's defensible.  The only people who will be
bothered are existing programs that are expecting IndexError.  Are
there that many of those, given that I don't think [N] is even
documented?

-- 
Mike Orr <[EMAIL PROTECTED]>

--~--~---------~--~----~------------~-------~--~----~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to