Using Django, I am trying to output the total number of lots in each community.
A community has several lots, and there are several communities. Here is an example of what I am getting:
Total lots: 99.
This community only has 2 lots. There are 4 communities with a total of 9 lots between them.
The models and views seem correct. Is there a filter I am missing or a different way of writing this to get the correct result?
{% 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 %}
This logic:
{% for lot in community.lot_set.all %}{{ lots|length }}{% endfor %}
Iterates through each lot object. You then take the length of lots which as far as I can tell is not a variable in context. If you wanted to just count the objects:
{{ community.lot_set.count }}
would do.
Looking ahead though, you're going to want to get counts of Active, Sold, Inactive, etc, and to do this efficiently you should look into annotating the queryset and doing this counting in the database: