python - 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 篇文章
解决方案
问题是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 }}
推荐阅读
- angular - Angular Karma/Jasmine 单元测试用例:测试范围
- android - 如何从 Cordova 应用程序编写 API 到电子邮件
- vb.net - 如何在运行时动态创建多个控件
- html - “职位:绝对”的祖父母、父母和子女管理问题
- python - Django:使用网络视图检查
- javascript - 我想从更改键的 javascript 数组中获取 php 数组
- d3.js - D3 使用自定义比例填充颜色
- powershell - 使用 PowerShell 重启网络 PC 的服务
- python - 使用 Overpass API 查询所有道路并导出为多边形
- c# - C# AxMSTSCLib.AxMsTscAxNotSafeForScripting.connect() 成功但不显示远程 VM