【问题标题】:Django: Nested for loop do not work properlyDjango:嵌套的for循环不能正常工作
【发布时间】:2021-08-26 22:40:47
【问题描述】:

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

在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

在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 篇文章

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

作者 1:3 3 2 篇文章

作者2:3 3 2 篇文章

作者 3:3 3 2 篇文章

【问题讨论】:

    标签: python html django


    【解决方案1】:

    问题在于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 }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      相关资源
      最近更新 更多