【发布时间】: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 篇文章
【问题讨论】: