Reputation: 693
I'm new to Django so please let me know if there is a better methodology than what I'm trying to do.
About project
I'm building an application that lists houses and the dates of inspection reports. If the house fails an inspection, then it gets re-inspected approximately 30 days later.
The house details (name, address) are in one model, and the inspection reports (date, violations) are kept in another model. This is a one (house) to many (inspections) relationship.
Web page renders with table like so:
HOUSE |TYPE |INSPECTION |VIOLATIONS
------------|----------|---------------|-----------:
Grand Place |Private | |
| |Nov. 21, 2011 |20
| |Dec. 20, 2011 |5
| |Oct. 20, 2012 |1
Would like to see:
I'd like to color code the inspection field so that if there is more than one inspection for that year, then it is red, otherwise it is green. This is to indicate that the house previously failed an inspection.
An added bonus would be to also have a separating border between the years to improve readability.
Relevant code from template:
<div style="clear: both; font-size: .8em;">
{% if house_information_list %}
<table style="border: none; max-width: 600px;">
<th><tr style="border-bottom: 1px solid #333; font-weight: bold;">
<td>House</td>
<td>Type</td>
<td>Inspection</td>
<td>Violations</td>
<td>Inspection Report</td>
</tr></th>
{% for house in house_information_list %}
<tr>
<td>
<b>{{ house.house_name }}</b>
</td>
<td style="width: 120px;">
{{ house.house_type }}
</td>
<td style="width: 100px;"></td>
<td style="width: 80px;"></td>
<td style="width: 120px;"></td>
</tr>
{% for report in house.inspectionreport_set.all %}
<tr>
<td></td>
<td></td>
<td>
{{ report.inspection_date }}
</td>
<td style="text-align: right; padding-right: 20px;">
{{ report.inspection_violations }}
</td>
<td></td>
</tr>
{% endfor %}
{% endfor %}
</table>
{% else %}
<p>Uh oh!</p>
{% endif %}
</div>
Upvotes: 0
Views: 62
Reputation: 37319
To do exactly what you describe, one approach would be to use the regroup
template tag on the reports and check year.list|length
in an if
block. That would also support the border between years.
{% with house.inspectionreport_set.all as reports %}
{% regroup reports by inspection_date.year as years_list %}
{% for year in years_list %}
{# some year indicator #}
{% if year.list|length > 1 %}
{# red #}
{% else %}
{# green #}
{% endif %}
{% endfor %}
{% endwith %}
You might need to use a custom method to get the year from the inspection date, I don't remember offhand whether dotted lookup will work in the regroup
field.
Alternatively, you could store a success/failure boolean on the inspection report and use the ifchanged
template tag to do year borders. That's probably what I'd do, unless it's really intended that a failure in December doesn't get flagged in red if it's reinspected in January of the next year.
Upvotes: 1