簡體   English   中英

django 外鍵模型計數

[英]django count of foreign key 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)

我的看法:

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

現在視圖顯示所有答案的計數。 我如何通過Question模型過濾它?

您可以使用.annotate()獲取與每個question相關的answers計數。

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

通過這樣做,每個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

最終代碼:

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

查看文檔
您可以注釋查詢,例如:

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

但是,將代碼重構為此。 刪除答案的數量:

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

現在,在all_question.html 只需使用:

{% 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 %}

它更有效率。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM