How to check if a queryset is empty?

Viewed 6650

Pagination code:

try:
    page = paginator.page(page_number)
    print(page.object_list)

So the following output is the result of print(page.object_list) for my pagination:

<QuerySet [<Comment: I can't believe it's happeinig>, <Comment: Just trying to fill up the comments>, <Comment: Another one!>, <Comment: Evenmore noe>, <Comment: Something>, <Comment: Lol>, <Comment: Are comments showing up?>, <Comment: Great for the economy.>, <Comment: honestly>, <Comment: Even though the the onlyEven though the only one to udnertstnaf!>]>
<QuerySet [<Comment: Yeah it's crazy how fast aswell. It's very awesome how it's doing atm. >]>
<QuerySet []>
<QuerySet [<Comment: Sure>, <Comment: No worries>]>
<QuerySet []>
<QuerySet []>
<QuerySet [<Comment: attempt 2!>]>
<QuerySet [<Comment: Attempt 3!>]>
<QuerySet []>
<QuerySet [<Comment: 12>]>
<QuerySet []>
<QuerySet [<Comment: Somewhere?>]>
<QuerySet []>
<QuerySet [<Comment: lol>]>
<QuerySet []>
<QuerySet [<Comment: 12>]>
<QuerySet []>

As you can see I have empty querysets, and these are causing errors in my code. I therefore would like to iterate over these querysets and spot the empty ones. I tried to add this for loop:

for i in page.object_list:
    if len(i) < 0:

but I get an error:

TypeError at /news/11/
object of type 'Comment' has no len()

Any help appreciated.

Trying to delete the a queryset if it is empty:

try:
    page = paginator.page(page_number)
    if page.object_list:
        pass
    else:
        page.delete()

Error:

AttributeError at /news/11/
'CustomPage' object has no attribute 'delete'  
3 Answers

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

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

Another way is :

if page.object_list.count() == 0:
  #Empty Result
else:
  #Something
Related