为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

拉莫斯之舞 2021-04-05 10:08:07
views.pydef 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 %}(只是试图传达我试图做的逻辑)。
查看完整描述

3 回答

?
大话西游666

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


查看完整回答
反对 回复 2021-04-06
?
九州编程

TA贡献1785条经验 获得超4个赞

我认为您可以这样做。声明一个字典和一个清单,例如:


topic_dict = {}

topic_list = []

在循环中构建字典,例如


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

然后在同一个循环内将此字典追加到类似列表


topic_list.append(topic_dict)

因此,最后它将为您提供一个包含字典的列表,您可以轻松地在模板内部循环浏览这些字典。


查看完整回答
反对 回复 2021-04-06
  • 3 回答
  • 0 关注
  • 353 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号