kater
kater

Reputation: 139

Big django queryset in Python's if conditional expression

I have a queryset that was used in below code.

result = 1 if queryset else 0

In case of small queryset it's okay but when queryset gets bigger (more than 500 000 results) program freezes, it takes some time to stop it.

What is happening behind the scenes when Django's queryset is tested in the code above? Is some extra work performed during that check?

Even though the queryset is big, there is no problem with calling count() or iterator() or any other methods, it is that conditional expression where the problem appears.

Edit:
Queryset is too big. It populates Queryset's self._result_cache. Same thing happens for len() and iterating over queryset in a for loop.

Upvotes: 3

Views: 166

Answers (1)

Selcuk
Selcuk

Reputation: 59444

Python will either use the __bool__ or __len__ methods to test the truth value of an object, and it looks like the implementation for the Queryset class fetches all records:

https://github.com/django/django/blob/master/django/db/models/query.py#L279

def __bool__(self):
    self._fetch_all()
    return bool(self._result_cache)

It might be a better idea to use if queryset.count() or if queryset.exists() if that's what you want.

Upvotes: 4

Related Questions