首页 > 解决方案 > Django:嵌套的for循环不能正常工作

问题描述

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

在模型.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

在views.py中:

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 输出是这样的:

作者1:2篇

作者2:3篇

作者3:3篇

ETC

但这不会发生,输出是:

作者 1:3 3 2 篇文章

作者 2:3 3 2 篇文章

作者 3:3 3 2 篇文章

标签: pythonhtmldjango

解决方案


问题是authorAticles = Author.objects.annotate(numberOfArticles=Count('article'))返回作者,而不是文章,也不是他们的计数。所以稍后在这里:

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

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

类似的东西{{ author.article_set.count }}应该可以为每个作者计算所有这些。

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

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

然后在模板中引用它:

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

推荐阅读