You can use .annotate()
to get the count of answers
associated with each question
.
from django.db.models import Count
questions = Question.objects.annotate(number_of_answers=Count('answer')) # annotate the queryset
By doing this, each question
object will have an extra attribute number_of_answers
having the value of number of answers
associated to each question
.
questions[0].number_of_answers # access the number of answers associated with a question using 'number_of_answers' attribute
Final Code:
from django.db.models import Count
def all_questions(request):
questions = Question.objects.annotate(number_of_answers=Count('answer'))
return render(request, 'all_questions.html', {
'questions':questions})
In your template, then you can do something like:
{% for question in questions %}
{{question.number_of_answers}} # displays the number of answers associated with this question
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…