[Django]-How to check if a queryset is empty?

5πŸ‘

βœ…

You can test the QuerySet directly using an if clause. This would cause the QuerySet to be evaluated. Empty QuerySets (or empty lists) are falsy:

page = paginator.page(page_number)
if page.object_list:
    ...

If you want to iterate on the QuerySet, there’s no need to test for emptiness. Just use the for clause:

for obj in page.object_list: # empty QuerySet gets zero iterations
   ...

3πŸ‘

You can use exists(emphasis mine)

page.object_list.exists()

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 as a normal QuerySet query.

exists() is useful for searches relating to both object membership in a QuerySet and to the existence of any objects in a QuerySet, particularly in the context of a large QuerySet.

Although, it would be much better to filter the queryset before creating the paginator

πŸ‘€Sayse

0πŸ‘

Another way is :

if page.object_list.count() == 0:
  #Empty Result
else:
  #Something
πŸ‘€helpdoc

Leave a comment