Wednesday, July 21, 2010

How retrieve a single object rather than a list from DB?

Hi,

I want to select a single object or get None if my query does not
return a single object.


So far here is what i have found in the docs (http://
docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets):

------------------------------------
To retrieve a single object rather than a list (e.g. SELECT foo FROM
bar LIMIT 1), use a simple index instead of a slice. For example,
this returns the first Entry in the database, after ordering entries
alphabetically by headline:

>>> Entry.objects.order_by('headline')[0]

This is roughly equivalent to:

>>> Entry.objects.order_by('headline')[0:1].get()

Note, however, that the first of these will raise IndexError while the
second will raise DoesNotExist if no objects match the given criteria.
See get() for more details.
------------------------------------

Unfortunately, both ways generate an exception, which is bad.

Is there some kind of way to either get a single object and evaluate
the query, or get None instead?
NHibernate and LINQ has a way to do that, so i wonder does Django have
that


Darius

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate