Google App Engine Migrating from db to ndb datastore – creating a commenting system with webapp2 (part 2)

This post will cover fetching comments associated with a particular post and rendering the comments using Jinja2 template. The concept is pretty much the same as using the db model.

Check out the below code.

class Reply(ndb.Model):
    content = ndb.TextProperty(required = True)
    p_key= ndb.KeyProperty(Post)
    created = ndb.DateTimeProperty(auto_now_add = True)
    last_modified = ndb.DateTimeProperty(auto_now = True)

class PostPage(Handler):
    def get(self, post_id):
        key = ndb.Key('Post', int(post_id), parent=question_key())
        post = key.get()

        params = dict(post=post)

        #fetch all the comments and filter it by key
        if Reply.query():
            reply = Reply.query(Reply.p_key == key)
            params['reply'] = reply

        self.render("permalink.html", **params)

I first built a key of the post and fetched the post to pass it into params. Then I fetched all the comments using the query method and filtered it by setting the key of the comments(“p_key” property inside the “Reply” entity) to the key of the post. The key is stored into the Reply entity so you can only filter the comments associated with the post.

Lastly, I rendered my HTML template.

The below code is the template.

<div>
    {% for r in reply %}
        <div>{{r.content | safe}}</div>
    {% endfor %}
</div>

Now you have a commenting system for your web app!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s