Отображение в PDF уникальных значений и подсчет каждого уникального значения

У меня возникают трудности с отображением в pdf всех уникальных значений категории и подкатегории в сравнении с количеством каждой категории под тремя строгими колонками, которые являются степенью тяжести. Серьезность имеет три варианта (выделены жирным шрифтом).

В PDF должно быть четыре колонки:

Причина аварии | Подкатегория причины аварии | Повреждение имущества | Смертельный | Несмертельный

Виды

def fetch_resources(uri, rel):
    path = os.path.join(uri.replace(settings.STATIC_URL, ""))
    return path

def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html  = template.render(context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result, link_callback=fetch_resources)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

class GenerateInvoice(View):
    def get(self, request, *args, **kwargs):
        try:
            incident_general = IncidentGeneral.objects.filter(user_report__status = 2).distinct('accident_factor')   #you can filter using order_id as well
        except:
            return HttpResponse("505 Not Found")
        data = {
            'incident_general': incident_general,

        }
        pdf = render_to_pdf('pages/generate_report_pdf.html', data)
    
        if pdf:
            response = HttpResponse(pdf, content_type='application/pdf')
            filename = "Accident Causation" #%(data['incident_general.id'])
            content = "inline; filename='%s'" %(filename)

            content = "attachment; filename=%s" %(filename)
            response['Content-Disposition'] = content
            return response
        return HttpResponse("Not found")

Модели

class AccidentCausation(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    category = models.CharField(max_length=250)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.category

class AccidentCausationSub(models.Model):
    accident_factor = models.ForeignKey(AccidentCausation, on_delete=models.CASCADE)
    sub_category = models.CharField(max_length=250, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.sub_category

class IncidentGeneral(models.Model):
  


    SEVERITY = (
        ('Damage to Property', 'Damage to Property'),
        ('Fatal', 'Fatal'),
        ('Non-Fatal', 'Non-Fatal'),
    )

    user = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, null=True, blank=True)
    user_report = models.OneToOneField(UserReport, on_delete=models.CASCADE)
    accident_factor = models.ForeignKey(AccidentCausation, on_delete=models.SET_NULL, blank=True, null=True)
    accident_subcategory = models.ForeignKey(AccidentCausationSub, on_delete=models.SET_NULL, blank=True, null=True)
    collision_type = models.ForeignKey(CollisionType, on_delete=models.SET_NULL, blank=True, null=True)
    collision_subcategory = models.ForeignKey(CollisionTypeSub, on_delete=models.SET_NULL, blank=True, null=True)
    crash_type = models.ForeignKey(CrashType, on_delete=models.SET_NULL, blank=True, null=True)
    weather =  models.CharField(choices=WEATHER, max_length=250,blank=True, null=True)
    light =  models.CharField(choices=LIGHT,max_length=250, blank=True, null=True)
    severity = models.CharField(choices=SEVERITY, max_length=250, blank=True, null=True)
    movement_code = models.CharField(max_length=250, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

HTML

<tr>
              <th scope="col">ACCIDENT CAUSATION</th>
              <th scope="col">ACCIDENT CAUSATION SUB-CATEGORY</th>
              <th scope="col">DAMAGE TO PROPERTY</th>
              <th scope="col">FATAL</th>
              <th scope="col">NON-FATAL</th>
          </tr>
      </thead>
      <tbody>
          {% for i in incident_general %}
          <tr>
              <td scope="row">{{i.accident_subcategory.accident_factor.category}}</td>
              <td scope="row">{{i.accident_subcategory.sub_category}}</td>

{%endfor%}

Вернуться на верх