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.
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 ?
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.
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.
Just use exists
self.assertFalse(Tag.objects.get_for_object(Animal.objects.get(pk=1)).exists())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With