[Answered ]-Annotate causes ProgrammingError: must appear in the GROUP BY clause or be used in an aggregate function

2👍

TLDR; use only

Whenever you call only() it replaces the set of fields to load
immediately. The method’s name is mnemonic: only those fields are
loaded immediately; the remainder are deferred. Thus, successive calls
to only() result in only the final fields being considered:

Django tries to be database agnostic but it isn’t easy, because mysql and sqlite in particular have a lot of non standard behavior. One of them centers around aggregation. Whereas postgresql is a lot closer to standards compliance. This is best explained in the mysql 5.7 manual

SQL92 and earlier does not permit queries for which the select list,
HAVING condition, or ORDER BY list refer to nonaggregated columns that
are neither named in the GROUP BY clause nor are functionally
dependent on (uniquely determined by) GROUP BY columns.

The problem here is that your query selects all the columns (as is the default with django) but some of them do not have meaningfull values when you use an aggregation. For example you have 100 students in 10 classrooms and each of them have a grade. You select the count of students in each class with an aggregate. You want to show the grade as well. But whose grade do you show?

Thus use the only function limit the columns that are selected by django.

👤e4c5

Leave a comment