Django:嵌套for循环不能正常工作



我们有两个表,它们有多对一的关系。

in models.py:

class Author(models.Model):
name     = models.CharField(max_length=100, null=False)
username = models.CharField(max_length=35, null=False)
def __str__(self):
return self.name
class Article(models.Model):
CATEGOTY = (
('programming', 'programming'),
('other', 'other')
)
title    = models.CharField(max_length=100, null=False)
content  = models.TextField(null=False)
category = models.CharField(max_length=100, choices=CATEGOTY, null=False)
creation = models.DateTimeField(auto_now_add=True)
author   = models.ForeignKey(Author, on_delete=models.CASCADE)
def __str__(self):
return self.title

def articles(request):
authors                = Author.objects.all()
articles               = Article.objects.all()
totalArticles          = articles.count()
authorAticles = Author.objects.annotate(numberOfArticles=Count('article'))
return render(request, 'articles/article.html', {
'articles'     : articles,
'authors'      : authors,
'totalArticles': totalArticles,
'authorAticles': authorAticles
})

和HTML代码:

<div class="container mb-3 p-3" id="author-aricle">
<div class="row">
<div class="col-sm">
totle articles: {{totalArticles}}
</div>
{% for author in  authors %}
<div class="col-sm">
{{author}}: 
{% for authorAticle in authorAticles %}
{{authorAticle.numberOfArticles}}
{% endfor %}
articles
</div>
{% endfor %}
</div>
</div>

我希望html输出显示每个作者在其名称旁边的文章数这意味着每个作者有多少篇文章?我希望html输出是这样的:

author1: 2 articles

作者2:3篇文章

author3: 3 articles

,但这没有发生,输出是:

author1: 3 3 2 articles

author2: 3 3 2 articles

author3: 3 3 2 articles

问题是authorAticles = Author.objects.annotate(numberOfArticles=Count('article'))返回Authors,而不是Articles,也不是它们的计数。所以后面这里:

{{author}}: 
{% for authorAticle in authorAticles %}

对于每个作者,遍历所有作者。

{{ author.article_set.count }}这样的东西应该可以计算每个作者的所有内容。

或者如果你喜欢使用注释,只需将其添加到作者过滤:

authors = Author.objects.annotate(numberOfArticles=Count('article'))

,然后在模板中引用它:

{{ author }}:
{{ author.numberOfArticles }}

最新更新