Hi, This is exactly what i do not want - to manually catch exceptions. get_or_none function is what i need, but sad it's not here yet.
I hope when i will get to know python better, i will learn how to add methods to all instances of some class, then i could add this method myself. I know with javascript prototyping inheritance that is easily possible. Not sure about python though Thanks for the answer. That is sufficient On 21 July, 19:23, Michael <newmani...@gmail.com> wrote: > On Wed, Jul 21, 2010 at 12:04 PM, Darius Damalakas < > > > > darius.damala...@gmail.com> wrote: > > 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 > > try: > obj = Entry.objects.order_by('headline')[0:1].get() > except Entry.DoesNotExist: > obj = None > > This is pretty standard. There has been some discussion on a get_or_none > style function on querysets, but I think we will have to wait a version for > it. > > Also look up django.shortcuts.get_object_or_404 > > Hope that helps, > > Michael -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.