2016-05-05 3 views
0

私はテーブルを持つテンプレートを持っています。各オブジェクトは関連するオブジェクトを持つことができます。これを仮定すると、私がする必要があるのは、各オブジェクトがその関連オブジェクトを持っているかどうかをチェックすることです。テーブルにない場合、関連するオブジェクトを作成するためのリンクを設定するフィールドがありますが、このオブジェクトを表示するためのアイコンが表示されています。Djangoは、クエリのすべてのオブジェクトをチェックして、関連するオブジェクトがあるかどうかを確認し、テンプレートでこれを使用します。

私は "親"オブジェクトの1つを使うことができますが、クエリに複数のオブジェクトがある場合はどうすればよいか分かりません。

モデルを確認するには:

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) 

が、これが私の見解である

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 

(1つの関連オブジェクトを持っている私はすでに知っている1つのオブジェクトのみをチェックする)と、テンプレート内の

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

私は従業員に対応するすべての事故を、また各事故に備える必要がありますtこれがAccidentCertificateを持っているかどうかをチェックし、証明書を見るためにリンクをテーブルに置いていれば、証明書を作るためのリンクを入れない。

+0

はそれが事故のために、複数の事故証明書が存在することができるようになりますか? – AKS

答えて

1

カウント注釈を使用して、関連する証明書の数を各事故に追加し、その番号をテンプレートの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 %} 
+0

ありがとう非常に!!!!! – marcosgue

関連する問題