我有以下代码;
视图.py
def render_blog_topics(request, topic):
categories = get_list_or_404(Category, name=topic)
"""for category in categories:
for topic in category.topics.all():
topic_posts += Post.objects.all().filter(topic = topic).order_by('topic')
print Post.objects.all().filter(topic = topic).order_by('topic').query
print topic_posts"""
all_data = []
all_topics = Topic.objects.all()
def loop_topic():
for topic in all_topics:
current_data = {}
current_posts = []
current_posts.append(Post.objects.filter(Q(topic=topic)))
# append more posts based on query here like Q(categorie__topic = each_topic) or something
current_data['topic'] = topic
current_data['posts'] = current_posts
all_data.append(current_data)
category_posts = Post.objects.filter(category= loop_topic())
print Post.objects.filter(category= loop_topic())
data = {
'categories': categories,
'TopicsForm': TopicsForm(),
'all_data' : all_data
}
print all_data
return render(request, 'blog_topics.html',data)
基本上,数据变量已经包含的内容用于有关导航元素和网站其他部分的标签。
我想要完成的是针对每个主题
for category in categories:
for topic in category.topics.all():
print topic
我想根据当前循环中的主题获取所有帖子,并让它构建一个我可以放入数据中的变量。
例如
Topic1 ---> 所有与 topic1 相关的帖子 Topic2 ---> 所有与 topic2 相关的帖子 .....依此类推
我如何构建一个单独的变量来保存主题以及与之相关的所有帖子,以便我可以在模板中循环遍历它;
{% for each topic %}
{% for each post in topic %}
{{ obj.title }}
{% endfor %}
{% endfor %}
(只是试图传达我试图做的事情的逻辑)。
解决方案
模板.py
{% for each_item in all_data %}
<div id="{{ each_item.topic }}" class="content_list">
<a class="title" href="">{{ each_item.topic }}</a>
<div class="list_container">
<ul>
{% for posts in each_item.posts %}
{% for post in posts %}
<li class="python">
<a href="">{{ post.title }}<br/>
<span class="date_comments">{{ post.date_created }} |
<span class="comments">12</span></span></a>
</li>
{% endfor %}
{% endfor %}
</ul>
</div>
</div>
{% endfor %}
视图.py
categories = get_list_or_404(Category, name=topic)
all_data = []
all_topics = Topic.objects.all()
category_posts = Post.objects.filter(category = categories[0])
print category_posts
for each_topic in all_topics:
current_data = {}
current_posts = []
current_posts.append(category_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)
data = {
'categories': categories,
'TopicsForm': TopicsForm(),
'all_data' : all_data
}
谢谢