django count of foreign key model

后端 未结 2 1724
别那么骄傲
别那么骄傲 2020-12-16 00:23

Hi i want to display a count of answers to my question model

my model:

class Question(models.Model):

    text = models.TextField()
    title = model         


        
相关标签:
2条回答
  • 2020-12-16 00:45

    See the docs
    You can annotate the Query, like:

    from django.db.models import Count
    questions = Question.objects.annotate(num_answer=Count('answer'))
    

    but, refactor the code to this. Remove the count of answers:

    def all_questions(request):
        questions = Question.objects.all()
        return render(request, 'all_questions.html', {'questions':questions })
    

    Now, in all_question.html. Just use :

    {% for question in questions %}
        Title: {{question.title}}
        Count Answers: {{question.answer_set.all|length}}
        {% for answer in question.answer_set.all %}
            {{answer.text}}
        {% endfor %}
    {% endfor %}
    

    It is more efficienty.

    0 讨论(0)
  • 2020-12-16 00:54

    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
    
    0 讨论(0)
提交回复
热议问题