Django Custom filter "a GROUP BY clause is required before HAVING"
I wrote a custom filter, linked to a MultipleChoiceFilter with 5 choices (0,1,1.75,2.5,3.25 and 4) :
def filtre_personnalise(self,queryset, name,value):
query=FicheIdentification.objects.none()
for i in value:
if i=='0':
query|=queryset.prefetch_related(Prefetch('entreprise',Entreprise.objects.all())).exclude(pk__in=[x.entreprise.siret for x in EvaluationGenerale.objects.all()])
else :
query|=queryset.prefetch_related(Prefetch('entreprise',Entreprise.objects.all())).annotate(note_moyenne=Avg('entreprise__evaluationgenerale__note')).filter(note_moyenne__range=(float(i),float(i)+0.75))
return query
If I tick each value individually everything works as expected, the returned queryset is what I want it to be.
Everything also works fine if I tick several values simultaneously as long as 0 is not one of them (eg. 1 and 4 work fine together).
But as soon as 0 is ticked with another value I get the following error :
a GROUP BY clause is required before HAVING
I honestly have no idea on why it behaves this way. I tried to replace | by .union but got this error :
django.db.utils.ProgrammingError: each UNION query must have the same number of columns
I think this one is related to the use of .annotate.
I solved the problem by replacing .annotate by .alias to avoid creating a new column. Then I joined the queries with .union instead of |.