[Fixed]-Django check every objects of a query to see if have related objects and use this on template

1👍

You can use a count annotation to add the number of related certificates to each accident, then use that number in an if statement in the template.

from django.db.models import Count
...
employee_accidents = Accident.objects.filter(employee=employee).annotate(certificate_count=Count('accidentcertificate'))

{% for a in accidents %}
...
{% if a.certificate_count == 0 %}
    <a href="whatever">Add new certificate</a>
{% endif %}
{% endfor %}

Leave a comment