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!
- [Django]-South migration: "database backend does not accept 0 as a value for AutoField" (mysql)
- [Django]-Rendering a value as text instead of field inside a Django Form
- [Django]-Django – Website Home Page
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)
- [Django]-Django: Arbitrary number of unnamed urls.py parameters
- [Django]-Django count RawQuerySet
- [Django]-ForeignKey to abstract class (generic relations)
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..
- [Django]-Django: Open uploaded file while still in memory; In the Form Clean method?
- [Django]-Table thumbnail_kvstore doesn't exist
- [Django]-Access web server on VirtualBox/Vagrant machine from host browser?