如何在Django中按类别分组

30byixjq  于 2022-12-01  发布在  Go
关注(0)|答案(1)|浏览(137)

我有一个显示在Django站点上的项目任务列表。但是我如何在模板中强制它以这种方式拆分项目呢?
我想做的是有章节标题:

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

**PROJECT 2**
Task 1
Task 2
k10s72fa

k10s72fa1#

假设你有两个模型,一个类别和一个帖子 (很像一个项目和一个任务)

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

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

您可以将类别传递给模板,如下所示:

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

在模板中,您可以执行以下操作:

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

相关问题