I’m trying to capture the queries which my code submits to the database by examining the contents of django.db.connection.queries
. For some reason though, after all the automatically produced setup queries are logged, no further queries are logged from my own code. The following test case demonstrates the behavior.
from django.test import TestCase from django.db import reset_queries, connection from django.contrib.auth.models import User from django.conf import settings class Test1(TestCase): def setUp(self): settings.DEBUG = True def test1(self): self.assert_(settings.DEBUG, 'DEBUG is False') reset_queries() #clears out all the setup queries User.objects.all() self.assert_(connection.queries, 'No queries')
And here are the results of running it:
Traceback (most recent call last): File "/Users/jacob/foo/bar_project/baz_application/tests.py", line 246, in test1 self.assert_(connection.queries) AssertionError: No queries
Would anyone be able to shed some light on this? Thanks.
Advertisement
Answer
You will not see any queries after executing User.objects.all()
. This is only to be expected. The reason? Querysets are lazy. Unless you do something with the queryset NO query will be triggered. To verify this hypothesis, try the following and see if the test passes.
class Test1(TestCase): def setUp(self): settings.DEBUG = True def test1(self): self.assert_(settings.DEBUG, 'DEBUG is False') reset_queries() #clears out all the setup queries print User.objects.all() # <============= Printing the queryset. self.assert_(connection.queries, 'No queries')