Eugenio
Eugenio

Reputation: 193

Django Template Tag - Get count from related models

How are you! I'm listing in html a list of registers (RegAcceso) and I want to include in each of them the amount of registers (Registros) connected to it through a foreign key.

class RegAcceso(models.Model):
    reg_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    fecha = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'{self.id} - {self.reg_user} - {self.fecha.strftime("%d/%m/%Y")}'

    class Meta:
        ordering = ['-fecha']


class Registro(models.Model):
    id_reg = models.ForeignKey(RegAcceso, on_delete=models.CASCADE)
    cuil = models.BigIntegerField()
    deduccion = models.CharField(max_length=50)
    tipo = models.CharField(max_length=50)
    dato1 = models.CharField(max_length=50)
    dato2 = models.CharField(max_length=50, blank=True, null=True)
    porc = models.CharField(max_length=3, blank=True, null=True)

    def __str__(self) -> str:
        return f'{self.id_reg.reg_user} - {self.id_reg.fecha.strftime("%d/%m/%Y")} - {self.cuil}'
@login_required
def siradig_view(request):
    listado = {}
    query_historia = RegAcceso.objects.filter(reg_user=request.user)

    if request.method == 'POST' and request.FILES.get('upload'):
        # TODO: Validar form
        listado = lista_zip(request.FILES['upload'])
        dire = lista_zip_ex(request.FILES['upload'])
        archivo_path = os.path.join(settings.TEMP_ROOT, 'ultima_carpeta.txt')
        with open(archivo_path, 'w') as f:
            f.write(dire)

    else:
        # Borro los archivos en carpeta temporal
        clean_folder(settings.TEMP_ROOT)

    my_context = {
        'listado': listado,
        'query_historia': query_historia,
    }

    return render(request, 'reader/home.html', my_context)
{% if query_historia %}
  <div class="card" style="width: 80%;">
    <ul class="list-group list-group-flush">
      {% for registro in query_historia %}
        <li class="list-group-item text-center">
          <a href="{% url 'historico' registro.id %}">{{ registro.fecha|date:"d/m/Y h:i a" }}{{ registro.count }}</a>
        </li>
      {% endfor %}
    </ul>
  </div>
{% endif %}

I'm stuck in the {{ registro.count }} part. Thank you in advance!

Upvotes: 0

Views: 161

Answers (1)

Damoiskii
Damoiskii

Reputation: 1370

What I'd suggest is adding related name to the Registro model FK field. For example:

class Registro(models.Model):
     id_reg = models.ForeignKey(RegAcceso, on_delete=models.CASCADE, related_name='registers')  # related_name='some name of your choice'

Then within the for loop in your template, you can count all Registro objects linked with each RegAccesoobject by referencing the related_name.

{% for registro in query_historia %}
     <li class="list-group-item text-center">
          <a href="{% url 'historico' registro.id %}">{{ registro.fecha|date:"d/m/Y h:i a" }}{{ registro.registers.count }}</a>
     </li>
{% endfor %}

That should work.

Upvotes: 1

Related Questions