使用Django标记获取每个对象中的对象总数

2024-04-19 16:03:59 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Django,我试图输出每个社区中的地块总数

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

Total lots: 99. 

这个社区只有两块地。共有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 %}

Tags: margincommunitydivimgcolh1md社区
1条回答
网友
1楼 · 发布于 2024-04-19 16:03:59

这种逻辑:

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

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

{{ community.lot_set.count }}

就行了

不过,展望未来,您会希望获得活动、售出、非活动等的计数,为了有效地进行此操作,您应该研究注释查询集并在数据库中进行此计数:

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

相关问题 更多 >