You can use: obj = next(iter(SomeModel.objects.filter(foo='bar')), None)
The 'iter' part is not particularly elegant, but it's the only one-liner known to me. -- Marijonas On Thu, Oct 11, 2012 at 3:45 PM, Ole Laursen <o...@iola.dk> wrote: > On Tuesday, October 9, 2012 7:15:55 PM UTC+2, ptone wrote: >> >> Earlier discussion >> https://groups.google.com/**forum/?fromgroups=#!topic/** >> django-developers/Saa5nbzqQ2Q<https://groups.google.com/forum/?fromgroups=#%21topic/django-developers/Saa5nbzqQ2Q> >> > > This was the thread I referred to. If was from 2006 and ended up being > about something else. > > >> tickets: >> > https://code.djangoproject.**com/ticket/17546<https://code.djangoproject.com/ticket/17546> >> > > Closed as dupe with no further analysis. > > >> https://code.djangoproject.**com/ticket/2659<https://code.djangoproject.com/ticket/2659> >> > > This is about a different API which is a bit more cumbersome. And it was > closed 6 years ago with a - "this could be feature creep". > > >> https://code.djangoproject.**com/ticket/11352<https://code.djangoproject.com/ticket/11352> >> > > This is a different proposal. > > > Just to expand slightly on my proposal - I don't actually want to get > anything else than None out of get. I just want something that makes > intuitive sense to a Python programmer and saves me from the annoying > try-except pattern or the related: > > objs = SomeClass.objects.filter(slug="xyz") > obj = None > if objs: > obj = objs[0] > > which I often end up shortening as > > obj = SomeClass.objects.filter(slug="xyz") > if obj: > obj = obj[0] > > You can't get a zero or one objects out of the ORM elegantly, something I > find I have to do relatively often in some code bases. I don't consider > try-except intuitive for a situation where the exception case isn't > exceptional. > > default=None makes sense when you are used to dicts, .first() or > .get_or_none() or .getnone() or .single() would be fine too. > > > Ole > > -- > You received this message because you are subscribed to the Google Groups > "Django developers" group. > To view this discussion on the web visit > https://groups.google.com/d/msg/django-developers/-/r8vZ2A9tIkgJ. > > To post to this group, send email to django-developers@googlegroups.com. > To unsubscribe from this group, send email to > django-developers+unsubscr...@googlegroups.com. > For more options, visit this group at > http://groups.google.com/group/django-developers?hl=en. > -- You received this message because you are subscribed to the Google Groups "Django developers" group. To post to this group, send email to django-developers@googlegroups.com. To unsubscribe from this group, send email to django-developers+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-developers?hl=en.