如何将GAE NDB的后代打印到Jinja2上?

2024-04-26 09:46:19 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我一直在修补jinja2和googleappengine。我只是在业余时间写一个小玩具应用程序;该应用程序有一个网页,其中显示了十个最新的帖子及其评论

当然,在Post对象被创建并存储在数据库中之后,所有的blog文章都可以在google数据存储中通过以下方式打印到页面上。我使用下面的查询来获取要显示的十篇文章

recent_blog_posts = ndb.gql("SELECT * FROM Posts ORDER BY created_at
DESC LIMIT 10;")

blogpage.html代码如下:

{% block content %}
{% for post in recent_blog_posts %}
    <div>
        <h3>{{post.title}}</h3>
        <pre>
            <p style="max-width: 100%;">{{post.post}}</p>
        </pre>
        <p>By: {{post.by_user}}</p>
        <!-- this is where I want the comments to go (explained below)-->
        <h4>Leave A Comment:</h4>
        <form method="post">
            <textarea name="comment" value="{{comment}}" style="height: 50px; width: 200px;"></textarea>
            <input type="hidden" name="post_key" value="{{post.key}}">
            <br>
            <button>Comment</button>
        </form>
    </div>
    <hr>
{% endfor %}
{% endblock %}

我只是迭代了上面查询中的10个对象来打印所有的博客文章。然而,这对我来说是个棘手的问题

我使用以下内容创建一个新的注释实例:

new_comment = Comments(comment = comment,
user = user.name, parent = ndb.Key(Posts, int(post_key)))
new_comment_key = new_comment.put()

当我将新的注释实例打印到屏幕上时,我只是想看看,它们都是用正确的父对象和自己的id正确打印出来的

现在,我不确定如何获取每个评论实例并将其与相应的帖子一起打印。我怎样才能做到呢

我到处搜索,甚至把它添加到上面的html模板中(代替上面html模板中的注释)

{% for comment in comment_query %}
    {{comment.comment}}
{% endfor %}

查询如下:

recent_comments = Comments.query(ancestor=ndb.Key(Posts, int(new_string))).order(-Comments.created_at).fetch(limit=3)

这显然只是打印出页面上所有post实例的所有Comments实例

提前谢谢


Tags: 对象实例keynamenewhtml文章comment
1条回答
网友
1楼 · 发布于 2024-04-26 09:46:19

只需在后端本身形成输出列表

recent_blog_posts = ndb.gql("SELECT * FROM Posts ORDER BY created_at
DESC LIMIT 10;")
posts_with_comments = []
for post in recent_blog_posts:
    recent_comments = Comments.query(ancestor=post.key).order(-Comments.created_at).fetch(limit=3)
    posts_with_comments.append([post, recent_commmnets])

然后遍历模板中的posts_with_comments,如

{% for post,comments in posts_with_comments %}
    <div>
        <h3>{{post.title}}</h3>
        <pre>
            <p style="max-width: 100%;">{{post.post}}</p>
        </pre>
        <p>By: {{post.by_user}}</p>
        <p> Comments: </p>
        {% for commnet in comments %}
           {{ comment }}
        {% endfor %}
{% endfor %}

相关问题 更多 >