On Wed, May 28, 2008 at 2:38 AM, radioflyer <[EMAIL PROTECTED]> wrote:
>
> Which is the most efficient, 'proper' way to get a count on a query
> set?
>
> t_results = Track.objects.filter(query).order_by('title')
> count = t_results.count()  # and pass 'count' to the template.
>
> or, in the template,
>
> <p>Your search returned {{t_results|length}} track{{t_results|
> pluralize}}.</p>

Which one is more efficient depends on other factors.

.count() performs a literal SELECT COUNT(*) ... query. This will be a
database hit every time you call it, but it is quite a fast operation.

len(queryset) (which is what gets called when you use the template
filter) will evaluate the full queryset into objects as a list, then
check the length of that list. However, one that length has been
evaluated, both the queryset and the length will be cached, so
subsequent calls to iterate over the queryset or obtain the length
will be very efficient.

So - if this is a once-off check of the length, you might find that
count() is a better option. However, if you are planning on doing
other operations with the queryset, checking length should be faster
in the long run.

Yours,
Russ Magee %-)

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

Reply via email to