On 10 November 2010 21:55, Shawn Milochik <sh...@milochik.com> wrote:
> The queryset returns zero or more instances of your model. So if
> there's only one result, you can just get the first item in the
> queryset by its index.
>
> For example:
>
> some_queryset = YourModel.objects.filter(**kwargs)
>
> if some_queryset.count() == 1:
>    x = some_queryset[0]
>    #x is now an instance of your model.
> else:
>    raise ValueError("%d results -- expected one!" % (some_queryset.count(),)

This is a very bad way of checking queryset length, because count()
actually creates a new QuerySet that gets executed (again!). Instead
use len() that will first check against queryset's internal cache. In
this special case of one element you can also write:

try:
    elem = YourModel.objects.get(**params)
except YourModel.DoesNotExists as e:
    # element was not found - do something with it
    pass
except YourModel.MultipleObjectsReturned as e:
    # there was more then one object that matches given params - if
params include a (primary) key this shouldn't happen
    pass

-- 
Łukasz Rekucki

-- 
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.

Reply via email to