Django 查询极慢

标签 django database performance django-queryset django-postgresql

我的 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 万次——有点太多了。 python profiler output

最佳答案

您应该首先尝试隔离问题。运行 manage.py shell 并运行以下命令:

scope = Scope.objects.get(pk='Esoterik I')
print scope

现在 django 查询只有在非常必要时才会执行。也就是说,如果您在第一行之后遇到缓慢问题,则问题出在查询创建的某个地方,这表明对象管理器存在问题。下一步是尝试通过 django 执行原始 SQL,并确保问题确实出在管理器上,而不是 django 中的一般错误。

如果您遇到第二行运行缓慢的问题,问题要么出在查询的实际执行上,要么出在数据的显示/打印上。您可以强制执行查询而不打印它(查看文档)以找出它是哪一个。

据我所知,但我认为解决此问题的最佳方法是将流程分解为不同的部分,并找出导致缓慢的部分

关于Django 查询极慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17970611/

相关文章:

database - "conflict serializable"和 "conflict equivalent"有什么区别?

database - 高性能分层文本搜索

python - 在 Python 3.4 中切片真的更慢吗?

django - 如何使用迁移框架添加 Django REST Framework 身份验证 token

javascript - 未捕获的类型错误 : $(. ..)。Datatable 不是函数。但在我调用 datatable 之前 Jquery 已经加载了

java - 在 Hibernate 中更新包含列表的对象

sql - 根据百分比查询投票表顶部项目

performance - 将大量带有 Guid ID 的对象传输到客户端

python - Google App Engine 是否适合作为 Lifestreaming 应用程序的平台?

python - 将到期时间设置为 django 密码重置 token