Django REST Framework: still N+1 queries after select_related, what am I missing?
One of my mentees brought this to me and now I am also stuck, which is humbling. We have a simple endpoint listing courses. Each course has a teacher (ForeignKey) and many tags (ManyToMany), and the serializer also shows how many students are enrolled.
class CourseSerializer(serializers.ModelSerializer):
teacher = TeacherSerializer()
tags = TagSerializer(many=True)
student_count = serializers.SerializerMethodField()
def get_student_count(self, obj):
return obj.enrollments.count()
# in the view
queryset = Course.objects.select_related("teacher").all()
Django debug toolbar shows 1 query for the courses with their teachers, which is good, but then 2 extra queries per course. With 50 courses that is 101 queries. select_related is there so what is happening? Postgres 15, Django 4.2.
Accepted answer
Written by
Grace Wanjiru
Backend dev at an edtech startup in Nairobi, and I mentor bootcamp grads on weekends. Django, Postgres, and a lot of patience for "my code worked yesterday".
Get the best of #select-star-anonymous weekly
One email each Monday with the most useful posts. No spam; unsubscribe in one click.
Comments
Sign in to join the conversation.
Sign in to commentAccepted answer