Q:

Django 1.10 Count on Models ForeignKey

I guess this must be simple, but I've been trying for hours and can't find anything to help.
I have 2 models. One for a Template Categories and another for a Template
I'm listing the Template Categories on the Homepage and for each Category I want to show how many templates have that category as a Foreign Key.
My code is as follows:
Models.py
class TemplateType(models.Model):
    type_title = models.CharField(max_length=60)
    type_description = models.TextField()
    file_count = models.ForeignKey('TemplateFile')

    def __str__(self):
        return self.type_title

    def get_absolute_url(self):
        return "/templates/%s/" %(self.id)

class TemplateFile(models.Model):
    template_type = models.ForeignKey(TemplateType, on_delete=models.DO_NOTHING)
    template_file_title = models.CharField(max_length=120)
    template_file_description = models.TextField()

    def __str__(self):
        return self.template_file_title

Views.py
from django.shortcuts import HttpResponse
from django.shortcuts import render, get_object_or_404
from django.db.models import Count

from .models import TemplateType
from .models import TemplateFile

def home(request):
    queryset = TemplateType.objects.all().order_by('type_title').annotate(Count('file_count'))

    context = {
        "object_list": queryset,
        "title": "Home",
    }
    return render(request, "index.html", context)

index.html
<div class="row">
        {% for obj in object_list %}
        <div class="template_type col-md-6">
            <a href="{{ obj.get_absolute_url }}">
                <h4>{{ obj.type_title }}</h4>
            </a>
            <p>{{ obj.type_short_description }}</p>
            <button class="btn btn-primary" type="button">Templates <span class="badge">{{ obj.file_count__count }}</span></button>
        </div>
        {% endfor %}
    </div>

Can somebody help please?

A:

Views.py
from django.shortcuts import HttpResponse
from django.shortcuts import render, get_object_or_404
from django.db.models import Count

from .models import TemplateType
from .models import TemplateFile

def home(request):
    queryset = TemplateType.objects.order_by('type_title').annotate(num_file=Count('file_count'))

    context = {
        "object_list": queryset,
        "title": "Home",
    }
    return render(request, "index.html", context)

Now object_list contains TemplateType objects. And you can acces num_file like : object_list[0].num_file. Use it in your template.
index.html
<div class="row">
        {% for obj in object_list %}
        <div class="template_type col-md-6">
            <a href="{{ obj.get_absolute_url }}">
                <h4>{{ obj.type_title }}</h4>
            </a>
            <p>{{ obj.type_short_description }}</p>
            <button class="btn btn-primary" type="button">Templates <span class="badge">{{ obj.num_file }}</span></button>
        </div>
        {% endfor %}
    </div>

