用django做web开发的人员,可能会经常遇到这样的情况:功能实现了,也可以正常的运行,就是页面打开的速度比较慢,不知道自己在views中所写def,访问了多少次数据库。
如何你现在还在为此所烦恼,现在这里可以给大家提供一个解决的方式。
其实django自身就带有这种统计的工具,来帮助大家计数。
from django.db import connection
class DoSomethingTests(django.test.TestCase):
def test_something_or_other(self):
num_queries_old = len(connection.queries)
do_something_in_the_database()
num_queries_new = len(connection.queries)
self.assertEqual(n, num_queries_new - num_queries_old)
使用方法是,在我们的views的相应def里,
def test_myself(self):
from django.conf import settings
from django.db import connection
settings.DEBUG = True
connection.queries = []
# Test code as normal
self.assert_(connection.queries)
settings.DEBUG = False
print len(connection.queries) # 次数输出的就是访问数据库的次数return