How to group by category in Django

I have a list of project tasks that show on a Django site. But how in the template can I force it to split the projects this way?

What I want to do is have section headings:

**PROJECT 1**
Task 1
Task 2
Task 3

**PROJECT 2**
Task 1
Task 2

Lets say you have two models, a category and a post (Much like a project and a task):

class Category(models.Model):
    name = ...
    ...

class Post(models.Model):
    title = ...
    category = models.ForeignKey(... related_name = "posts")
    ...

You could pass the categories to the templates like so:

def view(request):
    # get all categories
    cats = Category.objects.all().prefetch_related("posts") 
    # using prefetch related to prevent lazy-loading of queries, 
    # this might give a tiny performance increase reducing amount 
    # of database queries

    # render the template
    render(...., {"category":cats})

In the template you could then do:

{% for category in categories %}
    {{category.name}}
    {% for post in category.posts.all %}
        {{post.title}}
    {% endfor %}
{% endfor %}
Back to Top