I'm testing a view in Django that should remove all the tags from an object. For that i use this assertion:
self.assertEqual(list(Tag.objects.get_for_object(Animal.objects.get(pk=1))),[])
That works well, as i get an empty list in return. I wrapped the Django queryset in a list to avoid this:
AssertionError: [] != []
where an empty Django queryset is compared with an empty list.
But as this is not something i like a lot, i wondered if there is a nicer way to do that test.
只是使用exists
self.assertFalse(Tag.objects.get_for_object(Animal.objects.get(pk=1)).exists())
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!
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)
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..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.