在django中计算过滤查询中的所有类别对象



我正在拼命地计算模型中某个类别中的对象。更清楚地说:我正在抓取新闻文章,我有这个模型:

class News(models.Model):
title = models.CharField(max_length=2000)
link = models.CharField(max_length=2083, default="", unique=True)
published = models.DateTimeField()
desc = models.CharField(max_length=2083)
site = models.CharField(max_length=30, default="", blank=True, null=True)

该视图过滤对象并根据请求为其提供服务:

class SearchResultsView(ListView):
model = News
template_name = 'search_results.html'
context_object_name = 'articles'

def get_queryset(self):
query = self.request.GET.get('q')
min_dt = self.request.GET.get('qf')
max_dt = self.request.GET.get('qt')
object_list = News.objects.filter(Q (title__icontains=query)| 
Q (desc__icontains=query) & Q (published__range=(min_dt, max_dt))).order_by('-published')

我需要在我的html django网站上放上我为每个网站获得的文章数量

这是我的html

<div class="row">
<table>
<tbody>
<h2>{{ articles.count }} articles found in total </h2>
HERE I NEED TO PUT HOW MANY ARTICLES PER SITE BELOW IS 
THE ACTUAL LIST ON A TABLE
{% for a in articles %}
<tr>
<td>
<a href="{{ a.link }}">{{ a.title }}</a>
</td>
<td>
<p>
Source: {{ a.site }}
</p>
</td>
<td>
<p>
Published: {{ a.published }}
</p>
</td>
<td>
<p>
More info: {{ a.desc }}
</p>
</td>
</tr>
{% endfor %}
</tbody>
</table>

换句话说,我需要按站点分组并计算结果。

谢谢!

例如,如果您传递HTML模板的字典如下所示;

{ articles: object_list }

您可能需要计算该列表的大小,并将其作为单独的键值对添加到字典中,然后将其与articles数据一起读传。有两种方法可以做到这一点。您可以使用len()python函数,也可以使用Django ORM提供的count()函数。请参阅下面的示例,了解这两种方法及其权衡。

使用len()

{articles: object_list, number_of_articles: len(object_list)}

这种方法更有效,因为它避免了像count()那样再次访问该数据库。此外,使用len()非常适合您的场景,因为无论哪种方式都可以获取查询集。

使用count()

{articles: object_list, number_of_articles: object_list.count()}

这有点低效,因为count()查询将运行额外的数据库查询。仅当您不需要处理查询集并且只需要计数时,才使用count()

因此,在您的HTML中,您需要获得这样的计数:;

<h2>{{ number_of_articles }} articles found in total </h2>

最新更新