Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django count of foreign key model

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

my model:

class Question(models.Model):

    text = models.TextField()
    title = models.CharField(max_length=200)
    date = models.DateTimeField(default=datetime.datetime.now)
    author = models.ForeignKey(CustomUser)
    tags = models.ManyToManyField(Tags)

    def __str__(self):
        return self.title


class Answer(models.Model):

    text = models.TextField()
    date = models.DateTimeField(default=datetime.datetime.now)
    likes = models.IntegerField(default=0)
    author = models.ForeignKey(CustomUser)
    question = models.ForeignKey(Question)

my view:

def all_questions(request):

    questions = Question.objects.all()
    answers = Answer.objects.filter(question_id=questions).count()

    return render(request, 'all_questions.html', {
            'questions':questions, 'answers':answers })

Right now view displays count of all answers. How can i filter it by the Question model?

like image 534
Ivan Semochkin Avatar asked Oct 07 '15 17:10

Ivan Semochkin


People also ask

How does Django count foreign keys?

You can use . annotate() to get the count of answers associated with each question . 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 .

How to define many to one relationship in Django?

To define a one to many relationship in Django models you use the ForeignKey data type on the model that has the many records (e.g. on the Item model).


2 Answers

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
like image 145
Rahul Gupta Avatar answered Oct 16 '22 23:10

Rahul Gupta


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.

like image 5
Paulo Pessoa Avatar answered Oct 16 '22 21:10

Paulo Pessoa