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 %}
1条答案
按热度按时间k10s72fa1#
假设你有两个模型,一个类别和一个帖子 (很像一个项目和一个任务):
您可以将类别传递给模板,如下所示:
在模板中,您可以执行以下操作: