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 秒かかりますが、セットには 2 つのエントリしかありません。
データベース バックエンドは 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 万回呼び出されたようです。これは少し多すぎます。