如何在django数据库查询的嵌套for循环中创建字典?

时间:2013-06-27 11:15:20

标签: python django

我有以下代码;

views.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)

基本上,数据var已包含的内容用于有关导航元素和网站其他部分的标签。

我想要完成的是

中的每个主题
        for category in categories:
        for topic in category.topics.all():
            print topic

我希望根据当前循环中的主题获取所有帖子,并让它构建一个可以放在数据中的变量。

例如

主题1 --->所有与topic1相关的帖子 主题2 ---> ALl与topic2相关的帖子 ......等等第四个

我如何构建一个单独的变量来保存主题以及与之关联的所有帖子,以便我可以在模板中循环遍历;

{% 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 %}

views.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

        } 

由于

2 个答案:

答案 0 :(得分:0)

我认为你可以这样做。为ex: -

声明一个dict和一个列表
topic_dict = {}
topic_list = []

在你的循环中构建字典,比如

topic_dict = { 'title': topic['title'], 'author': topic['author'] }

然后在同一个循环中将此字典附加到类似

的列表中
topic_list.append(topic_dict)

所以最后它会给你一个包含字典的列表,你可以在模板中轻松地循环。

答案 1 :(得分:0)

以这种方式试试......

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