Django ORM annotation on prefetch_related
<p>How can I annotate a related model during prefetch_related query?</p>

<p>I have two models:</p>

<pre><code>class Subject(models.Model):
    ...

class Student(models.Model):
    subjects = models.ManyToManyField(Subject, related_name="students")
</code></pre>

<p>I want to retrieve in a single query <code>Subject</code> objects, the <code>Student</code> objects related to each one and number of <code>Subject</code>s each <code>Student</code> has.
I am trying to accomplish it with the following query:</p>

<p><code>Subject.objects.all().prefetch_related(
    Prefetch("student", queryset=Student.objects.all().annotate(subjects_count=Count("subject")))
)</code></p>

<p>But I get an SQL error:</p>

<p><code>OperationalError at /concerts/coldplay-en-madrid/
(1055, "Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'studentsubject.subject_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by")</code></p>