Monday, November 28, 2011

Re: Boolean test on queryset



On Monday, November 28, 2011, Adam Nelson <adam@yipit.com> wrote:
> Jirka,
> That doesn't solve the problem.  That will still do a very expensive count() operation on the queryset.  In fact, examples.count() is what happens when you do bool(examples) anyway.

I'm confused here -- examples.count() is definitely not the same as examples.__len__(), which is what you originally claimed that bool() was doing. examples.count() should issue a SELECT COUNT query, while len() iterates through the rows in the result set.

If you just need to know whether at least one row exists in the result, use examples.exists() -- that's what it's for.

https://docs.djangoproject.com/en/1.3/ref/models/querysets/#exists

From the (linked) docs:

> Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query. This means that calling QuerySet.exists() is faster than bool(some_query_set), but not by a large degree.


> Thanks,
> Adam
>
> On Mon, Nov 28, 2011 at 8:11 PM, Jirka Vejrazka <jirka.vejrazka@gmail.com> wrote:
>>
>> Hi Adam,
>>
>>  I tend to use:
>>
>>  if examples.count():
>>
>>    ...something...
>>
>>  HTH
>>
>>    Jirka
>>
>> --
>> 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.
>>
>
> --
> 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.
>

--
Regards,
Ian Clelland
<clelland@gmail.com>

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

No comments:

Post a Comment