[Answer]-Filter and compare years in Django

1👍

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.

Leave a comment