Django Restframework Optimization

Viewed 25

I have several models:

LessonSession, Lesson, Receipt, and Student

Lesson to LessonSession is 1 to Many

Lesson to Student is M2M

Receipt to Lesson is M2M

Student to Receipt is 1 to Many

I have a serializer that serializes LessonSession, and I want to get student's name inside Student and Receipt's id

so I have

receipts = self.lesson.receipt_set.all().select_related('student').values_list('id', 'student__name', named=True)

as a property of LessonSession

However, I cannot seem to correctly prefetch the receipt and student from LessonSession to avoid the N+1 problem.

right not I have

session = LessonSession.objects.all().prefetch_related('lesson').prefetch_related('lesson__students').prefetch_related('lesson__receipt_set')

and I still run into N+1 problem. How should I form my queryset to avoid this?

0 Answers
Related