models
class Article(models.Model):
title = models.CharField(max_length=100, verbose_name='文章标题')
class Org(models.Model):
name=models.CharField(max_length=30, verbose_name='公司名')
# 因为在博客项目中, 每个用户都是作者, 所以这里用author来表示用户
class Author(models.Model):
username = models.CharField(max_length=30, verbose_name='用户名')
articles_collected = models.ManyToManyField(to=Article, verbose_name='收藏的文章')
org = models.ForeignKey(to=Org, on_delete=models.CASCADE, null=True)
views
def orgs(request):
orgs = Org.objects.all()
for i in range(len(orgs)):
orgs[i].counts = orgs[i].author_set.all().values('articles_collected').count()
return render(request, "web/show-org.html", locals())
html
<table class="table" >
<thead>
<tr>
<th>名称</th>
<th>作者数量</th>
<th>文章数</th>
</tr>
</thead>
<tbody>
{% for row in orgs %}
<tr>
<td>{{ row.name }}</td>
<td>{{ row.author_set.all.count }}</td>
<td>{{ row.counts }}</td>
</tr>
{% endfor %}
主要看文章数row.counts是怎么处理显示的