i got a problem with an Django application. Queries on the model Scope are extremly slow and after some debugging i still got no clue where the problem is.
When i query the db like scope = Scope.objects.get(pk='Esoterik I')
in django it takes 5 to 10 seconds. The database has less than 10 entries and an index on the primary key. so it is way too slow. When executing the an equivalent query on the db like SELECT * FROM scope WHERE title='Esoterik I';
everything is ok, it takes only about 50ms.
Same problem happens if i do a query with a set of results like scope_list = Scope.objects.filter(members=some_user)
and then doing e.g. a print(scope_list) or iterating over the elements of the list. The query itself only takes a few ms but the print or iterating of the elements takes again like 5 to 10 seconds but the set has only two entries.
Database Backend is Postgresql. The Problem occurs the same on the local development server and apache.
here the code of the model:
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
update here the output of the python profiler. it seems query.py getting called 1.6 million times is a little too much.