3 回答

TA贡献1817条经验 获得超14个赞
尝试这种方式...
all_data = []
all_topics = Topic.objects.all()
categorie_posts = Post.objects.filter(categorie=categories)
for each_topic in all_topics:
current_data = {}
current_posts = []
current_posts.append(categorie_posts.filter(Q(topic=each_topic))
# append more posts based on query here like Q(categorie__topic = each_topic) or something
current_data['topic']=each_topic
current_data['posts'] = current_posts
all_data.append(current_data)
现在在模板中
{% for each_item in all_data %}
{% each_item.topic %}
{% for each_post in each_item.posts %}
{% each_post.title %}
{% each_post.content %}
{% endfor %}
{% endfor %}

TA贡献1785条经验 获得超4个赞
我认为您可以这样做。声明一个字典和一个清单,例如:
topic_dict = {}
topic_list = []
在循环中构建字典,例如
topic_dict = { 'title': topic['title'], 'author': topic['author'] }
然后在同一个循环内将此字典追加到类似列表
topic_list.append(topic_dict)
因此,最后它将为您提供一个包含字典的列表,您可以轻松地在模板内部循环浏览这些字典。
添加回答
举报