【问题标题】:How to access the items inside a list of query sets in django?如何访问 django 中查询集列表中的项目?
【发布时间】:2021-05-06 08:23:38
【问题描述】:

我必须使用 django 模板在单个页面上显示登录用户当前正在关注的多个用户的多个帖子。这是我写的函数:

def following(request, userName):
    userProfiles = FollowingList.objects.filter(listOwner = request.user)
    print("userProfile is ", userProfiles)
    
    listOfAllPosts = []

    #get posts against following
    for uP in userProfiles:
        getPosts = Posts.objects.filter(created_by = uP.followingID)
        print("Value of getPosts is", getPosts)


        for i in getPosts:
            listOfAllPosts.append(getPosts.values('created_by', 'postContent', 'dateAndTime'))

        print("Printing ALL posts", listOfAllPosts)
    return render(request, "network/following.html", {
            "listOfAllPosts" : listOfAllPosts
            })

我从 listOfAllPosts 得到的结果如下所示:

 [<QuerySet [{'created_by': 12, 'postContent': 'I have hot air balloon rides', 'dateAndTime': datetime.datetime(2021, 1, 30, 4, 21, 3, 192704, tzinfo=<UTC>)}, 
{'created_by': 12, 'postContent': 'adding second post', 'dateAndTime': datetime.datetime(2021, 2, 1, 7, 2, 51, 734510, tzinfo=<UTC>)}]>, 
<QuerySet [{'created_by': 11, 'postContent': 'Hello Sifaah', 'dateAndTime': datetime.datetime(2021, 1, 30, 4, 4, 31, 410825, tzinfo=<UTC>)}]>]

但是,我希望结果看起来像这样,这样我就可以轻松地将其打印在 HTML 页面上:

[<QuerySet[{'created_by': 12, 'postContent': 'I have hot air balloon rides', 'dateAndTime': datetime.datetime(2021, 1, 30, 4, 21, 3, 192704, tzinfo=<UTC>)}, 
{'created_by': 12, 'postContent': 'adding second post', 'dateAndTime': datetime.datetime(2021, 2, 1, 7, 2, 51, 734510, tzinfo=<UTC>)}, 
{'created_by': 11, 'postContent': 'Hello Sifaah', 'dateAndTime': datetime.datetime(2021, 1, 30, 4, 4, 31, 410825, tzinfo=<UTC>)}]>]

有没有办法做到这一点?

【问题讨论】:

  • 您只想将整个查询集作为字符串打印到您的 html 页面上?
  • 在您的循环中for i in getPosts: 为什么要一次又一次地将相同的查询集附加到列表中?你想追加i吗?

标签: python django list django-queryset


【解决方案1】:

如果你把这样的东西放在你的 following.html 文件中

{% for users_posts in listOfAllPosts %}
    {% for post in users_posts %}
        <p>{{ post }}</p>
    {% endfor %} 
{% endfor %}

您将在您的页面上获得如下所示的结果。

如果你把类似的东西放在你的 following.html 文件中

{% for users_posts in listOfAllPosts %}
    {% for post in users_posts %}
        <p>Created By: {{ post.created_by }}</p>
        <p>Post Content: {{ post.postContent }}</p>
        <p>Date: {{ post.dateAndTime }}</p>
    {% endfor %} 
{% endfor %}

你会得到一个看起来像这样的结果。

【讨论】:

  • 没问题。很高兴我能帮上忙!
猜你喜欢
  • 2017-11-28
  • 2017-08-02
  • 2012-11-26
  • 2020-01-16
  • 2020-09-14
  • 2018-10-31
  • 2018-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多