[Fixed]-How to count and compare in Django

1๐Ÿ‘

โœ…

If you want the sum of Question1 through Question10 for each row then do this:

from django.db.models import F

questions = Question.objects.annotate(s=F('question1') + F('question2') + F('question3') + F('question4') + F('question5') + F('question6') + F('question7') + F('question8') + F('question9') + F('question10'))

This will produce x number of results equal to the number of rows.
Then you can do:

for question in questions:
    print(question.s)  # prints the sum of Question1 - Question10

Or, if you just want the values (not Question objects) then:

sums = Question.objects.annotate(s=F('question1') + F('question2') + F('question3') + F('question4') + F('question5') + F('question6') + F('question7') + F('question8') + F('question9') + F('question10')).values('s')

[UPDATE]: It seems you are not looping correctly the questions QuerySet.

Here is what you have to do:

in your views.py have it like this:

questions = Question.objects.annotate(s=F('question1') + F('question2') + F('question3') + F('question4') + F('question5') + F('question6') + F('question7') + F('question8') + F('question9') + F('question10'))

...

return render(request, 'music/compare.html', {'questions': questions})

And then then in your HTML have it like this:

{% for question in questions %}
    <td>Question 1 </td>
    ...
    <td>{{question.name}} </td>
    ...
    <td>{{ question.s }} </td>

Edit 2 โ€“ changed views.py

def compare():
    questions = Question.objects.annotate(
        s=F('question1') + F('question2') + F('question3') + F('question4') + F('question5') + F('question6') + F(
            'question7') + F('question8') + F('question9') + F('question10'))

    ...

    return render(request, 'music/compare.html', {'questions': questions})

compare.html

{% for question in questions %}
    <td>Question 1 </td>
    ...
    <td>{{question.name}} </td>
    ...
    <td>{{ question.s }} </td>

{%endfor%}
</body>
๐Ÿ‘คnik_m

Leave a comment