我正在尝试通过检查
django.db.connection.queries的内容来捕获我的代码提交给数据库的查询.但是出于某种原因,在记录了所有自动生成的设置查询之后,不再从我自己的代码中记录进一步的查询.以下测试用例演示了该行为.
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')
以下是运行它的结果:
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
有人能够对此有所了解吗?谢谢.
解决方法
执行User.objects.all()后,您将看不到任何查询.这只是预料之中的.原因?查询集很懒惰.除非您对查询集执行某些操作,否则将不会触发查询.要验证此假设,请尝试以下操作并查看测试是否通过.
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')