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

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

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


例如


Topic1 --->与topic1相关的所有帖子Topic2 --->与topic2 ..... so相关的ALl帖子等等


我该如何构建一个包含主题和与之相关联的所有职位的单一变量,以便我可以在模板中循环浏览它;


{% for each topic %}

{% for each post in topic %}


{{ obj.title }}


{% endfor %}

{% endfor %}

(只是试图传达我试图做的逻辑)。


拉莫斯之舞
浏览 354回答 3
3回答

大话西游666

尝试这种方式...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 %}

九州编程

我认为您可以这样做。声明一个字典和一个清单,例如:topic_dict = {}topic_list = []在循环中构建字典,例如topic_dict = { 'title': topic['title'], 'author': topic['author'] }然后在同一个循环内将此字典追加到类似列表topic_list.append(topic_dict)因此,最后它将为您提供一个包含字典的列表,您可以轻松地在模板内部循环浏览这些字典。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python