﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
23662	QuerySet __nonzero__, __len__ cause queryset evaluation	Alexey Smishlayev	nobody	"Current implementation: https://github.com/django/django/blob/master/django/db/models/query.py

{{{
class QuerySet(object):
    ...
    def __nonzero__(self):
        self._fetch_all()
        return bool(self._result_cache)
    ...
    def __len__(self):
        self._fetch_all()
        return len(self._result_cache)
}}}

These methods call `self._fetch_all()`, thus evaluating the queryset. Although, this behaviour is [https://docs.djangoproject.com/en/1.7/ref/models/querysets/#when-querysets-are-evaluated documented], it is not obvious.

It seems logical to evaluate queryset, when casting it to a `list()` or iterating over it, but these particular cases have nothing to do with the queryset contents. There exist specific lazy methods (`QuerySet.exists()` and `QuerySet.count()` respectively) which, IMHO, should be used for the magic method implementation.

If I already have fetched the results of a queryset, I'm okay to call `__len__()` on them, but if they haven't been retrieved yet, I'd rather use `SQL COUNT()` instead. That is exactly, what QuerySet.count() does. The same goes for the `__nonzero__()` and `exists()`."	Cleanup/optimization	new	Database layer (models, ORM)	1.7	Normal				Unreviewed	1	0	0	0	0	1
