Django 检查查询的每个对象以查看是否有相关对象并在模板上使用它

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

我有一个带有 table 的模板,我有一个查询中的所有对象。每个对象可以有或没有相关的对象。假设这样,我需要做的是,对于每个对象检查是否有相关对象。如果不在 table 我有一个字段放一个 link 来创建一个相关的对象,但是如果有显示一个图标就可以看到这个对象。

我可以使用 "parent" 对象之一,但如果查询中有多个对象,我不知道该怎么做。

要检查的模型:

class Accident(models.Model):
    employee = models.ForeignKey(Employee)
    place = models.IntegerField(choices=ACCIDENT_PLACE, default=1)
    detail = models.CharField(max_length=255)
    clinic = models.ForeignKey(Clinic)
    is_urgency = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    created_by = models.ForeignKey(User,
                related_name='accidents_created_by',
                editable=False,
                blank=True,
                null=True
                )
    modified_by = models.ForeignKey(User,
                related_name='accidents_modified_by',
                editable=False,
                blank=True,
                null=True
                )


    class Meta:
        verbose_name = "accidente"
        verbose_name_plural = "accidentes"

    def __str__(self):
        return str(self.id)


class AccidentCertificate(models.Model):
    accident = models.ForeignKey(Accident)
    diagnostic = models.CharField(max_length=150)
    return_day = models.DateField()
    notes = models.CharField(max_length=255)
    medication = models.CharField(max_length=255)
    doctor = models.ForeignKey(Doctor)
    presented = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    created_by = models.ForeignKey(User,
                related_name='acc_certificates_created_by',
                editable=False,
                blank=True,
                null=True
                )
    modified_by = models.ForeignKey(User,
                related_name='acc_certificates_modified_by',
                editable=False,
                blank=True,
                null=True
                )


    class Meta:
        verbose_name = "certificado de accidente"
        verbose_name_plural = "certificados de accidente"
        ordering = ["-id"]


    def __str__(self):
        return str(self.id)

这是我的观点(只检查一个我已经知道有 1 个相关对象的对象)

class EmployeeDetailView(LoginRequiredMixin, DetailView):
    # Chequeamos que el usuario se encuentre logeado
    login_url = reverse_lazy('users:login')

    model = Employee
    template_name = 'employees/detail.html'
    pk_url_kwarg = 'employee_id'

    def get_context_data(self, **kwargs):
        context_object_name = 'employee'
        context = super(EmployeeDetailView, self).get_context_data(**kwargs)
        employee = context['employee']
        context['cuil'] = employee.cuil[:2]+'-'+employee.cuil[2:10]+'-'+employee.cuil[-1:]
        # Tomamos los accidentes correspondientes al empleado
        # y los pasamos al contexto
        employee_accidents = Accident.objects.filter(employee=employee)
        context['accidents'] = employee_accidents

        # Tomamos el certificado del accidente si existe
        accident_certificate = AccidentCertificate.objects.get(accident=employee_accidents)
        return context

并在模板中

<table class="table table-striped">
                    <thead>
                        <tr>
                            <th>ID Acc.</th>
                            <th>Fecha</th>
                            <th>Cant. Días</th>
                            <th>Locación</th>
                            <th>Detalle</th>
                            <th>Clinica</th>
                            <th>Urgencia</th>
                            <th>Cargado por</th>
                            <th>Certificado</th>
                            <th>Segimiento</th>
                        </tr>
                    </thead>

                    <tbody>
                        {% for a in accidents %}
                        <tr>
                            <td>{{ a.id }}</td>
                            <td>{{ a.created|date }}</td>
                            <td>-</td>
                            <td>{{ a.get_place_display }}</td>
                            <td>{{ a.detail }}</td>
                            <td>{{ a.clinic }}</td>
                            <td>
                            {% if a.is_urgency %}
                                Si
                            {% else %}
                                No
                            {% endif %}
                            </td>
                            <td>{{ a.created_by }}</td>
                            <td><a href="{% url 'accidents:add_certificate' a.id %}">{% bootstrap_icon "search" %}</a></td>
                            <td>{% bootstrap_icon "search" %}</td>
                        </tr>
                        {% empty %}
                        <p class="text-center">
                            <strong>NO HAY REGISTROS</strong>
                        </p>
                        {% endfor %}    
                    </tbody>
                </table>

好吧,在 sintesis 中,我需要记录与员工相对应的每起事故,并为每起事故检查是否有 AccidentCertificate,是否已将 link 放入 table 以查看证书,如果不放 link 来创建证书。

您可以使用计数注释为每个事故添加相关证书的数量,然后在模板的 if 语句中使用该数量。

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 %}