使用django标记获取每个对象内的对象总数

时间:2017-04-25 19:28:34

标签: python django

使用Django,我试图输出每个社区的总手数。

社区有几个地段,有几个社区。以下是我得到的一个例子:

Total lots: 99. 

这个社区只有2个地段。共有4个社区,总共有9个地段。

模型和视图似乎是正确的。是否存在我缺少的过滤器或以不同的方式编写此过滤器以获得正确的结果?

{% if community.is_active %}
<a class="panel-link" href="{% url 'community-detail' pk=community.id %}" %}>
    <div class="col-md-6 community_col">
        <div class="community_box">
            <div class="row">
                <br>
                <div class="col-md-4 community_img">
                    <img src="/media/{{ community.logo }}" alt="">
                </div>
                <div class="col-md-7 col-md-offset-1">
                    <h1 style="margin-bottom: -10px; margin-top: -15px;"><small>{{ community.name }}</small></h1>
                    <h4>{{ community.city }}, {{ community.state }}</h4>
                    <h6>Total lots: {% for lot in community.lot_set.all %}{{ lots|length }}{% endfor %}</h6>
                    <h6>Total Active lots: </h6>
                    <h6>Total Sold lots: </h6>
                    <h6>Total Inactive lots: </h6>
                </div>
            </div>
        </div>
    </div>
</a>
{% endif %}
{% endfor %}

1 个答案:

答案 0 :(得分:2)

这个逻辑:

{% for lot in community.lot_set.all %}{{ lots|length }}{% endfor %}

遍历每个批次对象。然后你取lots的长度,据我所知,它不是上下文中的变量。如果你只想计算对象:

{{ community.lot_set.count }}

会做的。

展望未来,您想要获得Active,Sold,Inactive等的计数,并且要有效地执行此操作,您应该查看注释查询集并在数据库中进行此计数:

https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset