title: Django rest framework How to fix many-to-many n+1 error?
body: <p>I have models:</p>
  <pre><code>class Group(models.Model):
      number = models.CharField(choices=CLASS_NUMBERS,
                                max_length=2,
                                verbose_name=&quot;Номер класса&quot;)
      name = models.CharField(max_length=20,
                              verbose_name=&quot;Название класса&quot;)
      group_teacher = models.ForeignKey('users.Teacher',
                                        on_delete=models.CASCADE,
                                        verbose_name=&quot;Классный руководитель&quot;,
                                        related_name='group_teacher')
      students = models.ManyToManyField('users.Student',
                                        verbose_name=&quot;Ученики&quot;, blank=True,
                                        related_name='group_students')
      code = models.CharField(max_length=8, unique=True)
  
  class Teacher(models.Model):
      user = models.OneToOneField(User, on_delete=models.CASCADE,
                                  verbose_name=&quot;Преподаватель&quot;, related_name='teacher_user')
  class Student(models.Model):
      user = models.OneToOneField(User,
                                  on_delete=models.CASCADE,
                                  verbose_name=&quot;Ученик&quot;, related_name='student_user')
  </code></pre>
  <p>and serializers:</p>
  <pre><code>class TeacherSerializer(ModelSerializer):
      class Meta:
          model = Teacher
          fields = [
              'user'
          ]
  
  class StudentsSerializer(ModelSerializer):
      class Meta:
          model = Student
          fields = [
              'user'
          ]
  
  class GroupSerializer(ModelSerializer):
      class Meta:
          model = Group
          fields = [
              'id',
              'number',
              'name',
              'code',
              'group_teacher',
              'students',
          ]
  </code></pre>
  <p>When I make an appeal to the api I get warnings:</p>
  <blockquote>
  <p>Potential n+1 query detected on <code>Teacher.user</code> Potential n+1 query
  detected on <code>Teacher.user</code> Potential n+1 query detected on
  <code>Student.user</code> Potential n+1 query detected on <code>Student.user</code>
  Potential n+1 query detected on <code>Student.user</code> Potential n+1 query
  detected on <code>Student.user</code></p>
  </blockquote>
  <p><a href="https://i.stack.imgur.com/KYaHb.png" rel="nofollow noreferrer">Queries</a></p>
  <p>my view set:</p>
  <pre><code>class GroupModelViewSet(viewsets.ModelViewSet):
      serializer_class = GroupSerializer
  
      def get_queryset(self):
          return Group.objects.all().prefetch_related('students')
  </code></pre>
  <p>How to fix these errors n+1, select_related does not let me select the model of students and teachers</p>