gpt4 book ai didi

python - 外键模型的django计数

转载 作者:太空狗 更新时间:2023-10-29 22:06:35 25 4
gpt4 key购买 nike

您好,我想显示我的问题模型的答案数

我的模型:

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)

我的看法:

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 })

现在 View 显示所有答案的计数。我如何通过 Question 模型过滤它?

最佳答案

您可以使用.annotate()获取与每个问题相关的答案的计数。

from django.db.models import Count
questions = Question.objects.annotate(number_of_answers=Count('answer')) # annotate the queryset

通过这样做,每个 question 对象都会有一个额外的属性 number_of_answers,其值为与每个 关联的 answers 数量问题

questions[0].number_of_answers # access the number of answers associated with a question using 'number_of_answers' attribute

最终代码:

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})

在您的模板中,您可以执行以下操作:

{% for question in questions %}
{{question.number_of_answers}} # displays the number of answers associated with this question

关于python - 外键模型的django计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32998591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com