【发布时间】:2013-07-31 23:48:44
【问题描述】:
我的 Django 应用程序有问题。对模型 Scope 的查询非常慢,经过一些调试后,我仍然不知道问题出在哪里。
当我像scope = Scope.objects.get(pk='Esoterik I') 这样查询数据库时,需要 5 到 10 秒。数据库的条目少于 10 个,并且主键上有一个索引,所以它太慢了。在数据库上执行类似SELECT * FROM scope WHERE title='Esoterik I'; 的等效查询时,一切正常,只需要大约 50 毫秒。
如果我查询像scope_list = Scope.objects.filter(members=some_user) 这样的一组结果,然后调用 print(scope_list) 或遍历列表元素,也会发生同样的问题。查询本身只需要几毫秒,但元素的打印或迭代再次需要 5 到 10 秒,但集合只有两个条目。
数据库后端是 Postgresql。同样的问题出现在本地开发服务器和apache上。
这里是模型的代码:
class Scope(models.Model):
title = models.CharField(primary_key=True, max_length=30)
## the semester the scope is linked with
assoc_semester = models.ForeignKey(Semester, null=True)
## the grade of the scope. can be Null if the scope is not a class
assoc_grade = models.ForeignKey(Grade, null=True)
## the timetable of the scope. can be null if the scope is not direct associated with a class
assoc_timetable = models.ForeignKey(Timetable, null=True)
## the associated subject of the scope
assoc_subject = models.ForeignKey(Subject)
## the calendar of the scope
assoc_calendar = models.ForeignKey(Calendar)
## the usergroup of the scope
assoc_usergroup = models.ForeignKey(Group)
members = models.ManyToManyField(User)
unread_count = None
更新
这是python分析器的输出。似乎 query.py 被调用了 160 万次 - 有点太多了。
【问题讨论】:
-
这个模型有
__unicode__()方法吗?可以发一下吗? -
是的,它有:
def __unicode__(self): return self.title -
我建议安装Django Debug Toolbar 以便您可以单独查看每个查询。它会让你更好地了解是什么让你放慢了速度。
-
您是从 django shell 还是从某个角度进行测试?
DEBUGsettings.py 中是真还是假? -
您提到的两个环境是否都连接到同一个 PostgreSQL 服务器,如果是,您是否在数据库设置中使用主机名或 IP 地址?
标签: django database performance django-queryset django-postgresql