I'm currently trying to compute the score
of a Survey
in SQL side only to be able to order survey by their scores.
My current logic is:
- Compute the real coefficient of my
Answer
- Make the sum of that coeficient for my
Question
(which can have multiplesAnswer
so I use Sum) - compute the number of
points
of my wholeSurvey
based on the sum of allQuestion
points (Question.point * sum(Answer.coef)) basically
Survey.objects.annotate(
answerresponse__realcoef=models.Case(
models.When(answerresponse__coef__isnull=True,
then=models.F('answerresponse__answer__coef')),
models.When(answerresponse__coef__isnull=False,
then=models.F('answerresponse__coef')),
output_field=models.FloatField(),
)
).annotate(
answerresponse__realcoef_sum=models.Sum(
models.F('answerresponse__realcoef')
)
).annotate(
points=models.Sum(
models.F('answerresponse__realcoef_sum') *
models.F('answerresponse__answer__question__points'),
output_field=models.IntegerField()
),
maxpoints=models.Sum('sections__question__points')
)
The database schema is something like:
Survey > Sections > Questions (points) > Answer (coef) > AnswerResponse (coef override)
and I get the following error:
FieldError: Cannot compute Sum('<CombinedExpression: F(answerresponse__realcoef_sum) * F(answerresponse__answer__question__points)>'): '<CombinedExpression: F(answerresponse__realcoef_sum) * F(answerresponse__answer__question__points)>' is an aggregate
which I understand as
That SQL part was not executed yet so you cannot rely on it
Is it possible to achieve that by keeping in the SQL side only?