次のコードがあります。
ビュー.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
現在ループ内にあるトピックに基づいてすべての投稿を取得し、データに配置できる変数を作成したいと考えています。
例えば
トピック 1 ---> トピック 1 に関連するすべての投稿 トピック 2 ---> トピック 2 に関連するすべての投稿 .....4 番目以降
トピックとそれに関連付けられたすべての投稿を保持する単一の変数を作成して、テンプレートでループできるようにするにはどうすればよいですか。
{% for each topic %}
{% for each post in topic %}
{{ obj.title }}
{% endfor %}
{% endfor %}
(私がやろうとしていることの論理を伝えようとしているだけです)。
解決
templating.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
}
ありがとう