获取对模板中过滤的子查询的计数 [英] Get count on filtered subqueries in template

查看:158
本文介绍了获取对模板中过滤的子查询的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个父模型和一个子模型,那么我如何可以列出父对象的所有子对象,并为每个子对象设置一个过滤的计数列出他们的时候?

If I have a parent model and a child model, how can I then list all child objects of a parent object, and have a filtered count for each child object, when listing them?

举个例子,假设我们有这些模型:

To give an example, assume we have these models:

class Category(models.Model):
    ...

class SubCategory(models.Model):
    category = models.ForeignKey(Category)
    ....

class Tag(models.Model):
    ....

class Article(models.Model)
    sub_category = models.ForeignKey(SubCategory)
    tag = models.ForeignKey(Tag)

然后我们有一个类别的DetailView,其中列出了该类别的所有子卡。在这个列表中,我们希望对每个子类别条目进行计数,其中包含的文章数量是一个特定的标签(也就是说,不是所有的 em>这个子类别的文章,这似乎更为微不足道的构建)。这样的东西:

Then we have a DetailView for a Category, in which all SubCatoegories for that Category are listed. In this list, we want to have a count on each SubCategory entry, on the number of articles it contains that also is of a certain tag (that is, not a count on all articles of that SubCategory, which seems much more trivial to build). Something like this:

{% for sub_category in category.sub_category_set.all %}
    {{ sub_category.name }} -- {{ sub_category.articles_set.filter(tag='xyz').all|length }}

我想这必须在某些方面在views.py和/或models.py中完成。我只是这样写,以澄清我的意思。那么我该怎么做到这样呢?

I guess this has to be done in the views.py and/or models.py in some way in the end. I just wrote it like this to clarify what I mean. So, how can I achieve something like this?

推荐答案

你是对的,你必须这样做。您可以使用注释获取每个子类别的过滤条目数:

You're right that you'll have to do this in the view. You can use annotation to get the number of filtered articles for each subcategory:

from django.db.models import Count

def my_view(request, other, arguments):
    ...
    subcategories = category.sub_category_set.filter(tag__tagname='xyz') \ 
                            .annotate(num_articles=Count('article__id'))
    ...

通过子类别到您的模板上下文中,您可以在模板中执行以下操作:

Pass subcategories to your template context, and in your template you can do this:

{% for subcategory in subcategories %}
    {{ subcategory.name }} -- {{ subcategory.num_articles }}
{% endfor %}

这篇关于获取对模板中过滤的子查询的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆