我试图在主页中的各个问题中显示问题和答案计数。我该怎么做?
Models.py
class Question(models.Model):
CATEGORY_CHOICES = (
('Math', 'Math'),
('Geography', 'Geography'),
('Biology', 'Biology'),
('Physics', 'Physics'),
('Chemistry', 'Chemistry'),
('Health', 'Health'),
('Computer Science', 'Computer Science'),
('History', 'History'),
)
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
description = models.TextField(max_length=3000)
slug = models.SlugField(max_length=140, unique=True)
date = models.DateField(null=True, default=datetime.date.today)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=50, default=None, null=True)
satisfied = models.BooleanField(default=False)
def __str__(self):
return self.title
def _get_unique_slug(self):
slug = slugify(self.title)
unique_slug = slug
num = 1
while Question.objects.filter(slug=unique_slug).exists():
unique_slug = '{}-{}'.format(slug, num)
num += 1
return unique_slug
def save(self, *args, **kwargs):
if not self.slug:
self.slug = self._get_unique_slug()
super().save()
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
user = models.ForeignKey(User, default=None)
answer = models.TextField(max_length=3000, null=True)
posted_on = models.DateField(default=datetime.datetime.now().date())
views.py
def home(request):
questions = Question.objects.all().order_by("-date")
numbers = Question.objects.all().count()
numbers2 = Answer.objects.all().count()
total_users = User.objects.all().count()
# PAGINATION ===============================
page = request.GET.get('page', 1)
paginator = Paginator(questions, 10)
try:
questions = paginator.page(page)
except PageNotAnInteger:
questions = paginator.page(1)
except EmptyPage:
questions = paginator.page(paginator.num_pages)
# counting answers on specific questions
empty = []
for a in Answer.objects.raw('SELECT id, question_id FROM main_answer'):
idd = a.id
question_id = (a.question_id)
empty.append(str(question_id))
repeatition = Counter(empty)
i = 0
trend_list = []
for x in range(len(repeatition)):
new = repeatition.most_common()[i][0]
trend_list.append(new)
i += 1
trend = Question.objects.get(id=trend_list[0])
print(trend_list)
print(trend)
# getting the answers to all questions in the front page
# search the questions ============
query= request.GET.get("q")
if query:
results = Question.objects.all()
questions = results.filter(title__icontains=query)
context = {
'questions': questions,
'numbers': numbers,
'numbers2': numbers2,
'total_users': total_users,
'trend': trend,
}
return render(request, 'main/index.html', context)
所以我需要的是在特定问题中显示问题和答案数量。 例如,在主页中,我显示了所有问题,我想要的是显示这些问题的数字。
什么是时间?答案:答案数。
答案 0 :(得分:1)
您可以使用答案数量annotate your queryset:
from django.db.models import Count
results = Question.objects.annotate(num_answers=Count('answer'))
然后,您可以在循环查询集时访问question.num_answers
:
{% for question in questions %}
{{ question.title }}
{{ question.num_answers }}
{% endfor %}