[英]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?我如何通过
Question
模型过滤它?
You can use .annotate()
to get the count of answers
associated with each question
.您可以使用
.annotate()
获取与每个question
相关的answers
计数。
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
.通过这样做,每个
question
对象将有一个额外的属性number_of_answers
具有与每个question
关联的answers
数量的值。
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
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
.现在,在
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.它更有效率。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.