Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i test for an empty queryset in Django?

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.

like image 837
marue Avatar asked Mar 12 '12 15:03

marue


People also ask

How do I check if a field is NULL in Django?

Unless you set null=True as well, your database should complain if you tried to enter a blank value. If your foreign key field can take null values, it will return None on null, so to check if it was "left blank", you could simply check if the field is None . What's the difference between is None and if not ?

IS NOT NULL in Django?

If a string-based field has null=True , that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it's redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL.

How do I find the length of a QuerySet?

If the QuerySet only exists to count the amount of rows, use count(). If the QuerySet is used elsewhere, i.e. in a loop, use len() or |length. Using count() here would issue another SELECT-query to count the rows, while len() simply counts the amount of cached results in the QuerySet.


1 Answers

Just use exists

self.assertFalse(Tag.objects.get_for_object(Animal.objects.get(pk=1)).exists())
like image 106
Chris Pratt Avatar answered Sep 27 '22 18:09

Chris Pratt