[Answered ]-Django pdf template count severity per row

1👍

you can of course do it by using Django annotate and Q Djagno aggregation

But, first of all, it is a good behaviour to use related_name in your foreign key field :

user = models.ForeignKey(User,related_name='incident_generals' on_delete=models.CASCADE, editable=False, null=True, blank=True)

By this way you can retrieve all related IncidentGeneral for a user by doing:

user.incident_generals.all()

It is possible without that but it is more suitable.

Next: if you want to retrieve all IncidentGeneral for a user with the count off severity status then you do :

from django.db.models import Count, Q
count_damage_to_property = Count('IncidentGeneral', filter=Q(severity='Damage to Property'))
count_fatal = Count('IncidentGeneral', filter=Q(severity='Fatal'))
count_non_fatal = Count('IncidentGeneral', filter=Q(severity='Non-Fatal'))
user_incident_generals = user.incident_generals.annotate(damage_to_property=count_damage_to_property).annotate(fatal=count_fatal).annotate(non_fatal=count_non_fatal)

You can now access each user IncidentGeneral count by severity level like this

for user_incident in user_incident_generals:
    nb_fatal = user_incident.fatal
    nb_non_fatal = user_incident.non_fatal

You can now do what you want.

Hope it will help you

Leave a comment