[Django]-How can i test for an empty queryset in Django?

43👍

Just use exists

self.assertFalse(Tag.objects.get_for_object(Animal.objects.get(pk=1)).exists())

9👍

self.assertEqual(Tag.objects.get_for_object(Animal.objects.get(pk=1).count(), 0)

You could also use len() if you want to enforce the queryset being evaluated as a list!

Alternately also assertQuerysetEqual is useful, you could do a comparison with an instance 0f django.db.models.query.EmptyQuerySet! But using count() should be the fastest way in most cases!

2👍

Chris’s answer works in this case. But, you can also use:

# the_list = list(some_queryset)   # converting a queryset into a list
self.assertEqual(len(the_list), 0)

# to go directly from queryset:
self.assertEqual(some_queryset.count(), 0)

0👍

As @Bernhard pointed, you could use self.assertQuerysetEquals, and compare your query set with an empty queryset, although it is an elegant solution, it may not be efficient.

The other solutions are also valid, but here is mine:

self.assertEquals(Tag.objects.get_for_object(Animal.objects.get(pk=1), None)

I strongly suggest to don’t convert a django queryset in a list. This is because converting a queryset to a list needs to load all the queryset in memory and convert it in a Python object.

For that purpose exist the queryset methods count(), exists() and etc..

Leave a comment