Search code examples
google-app-enginedata-modelingjinja2app-engine-ndbwebapp2

Google App Engine: Query for entities without URL arguments


Here's my data model:

BlogPost(ndb.Model):
    title = ndb.StringProperty()
    body = ndb.TextProperty()
    author_key = ndb.KeyProperty() 

Author(ndb.Model):
    name = ndb.StringProperty()
    fav_colour = ndb.StringProperty()

I am currently on my home page ('/'), and I would like to:

  • query for a list of all BlogPost entities, and
  • query for their respective authors to be displayed alongside a BlogPost entity.

I can query for all BlogPosts simply like this:

class BlogPostHandler(webapp2.RequestHandler): 
    def get(self):
        posts = BlogPost.query().fetch()
        self.render('index.html', posts = posts) #renders in Jinja2 template

The Jinja2 index.html template is this:

{% for p in posts %}
    {{p}}
    {{p's AUTHOR TO BE DISPLAYED HERE. Example: author.name, author.fav_colour}}    
{% endfor %}

So, I would like to know how I can display the Author entity which is associated with each BlogPost entity.

Thank you.


Solution

  • The best way to do this would be to denormalize the data and store a copy of the Author name in the BlogPost:

    BlogPost(ndb.Model):
        title = ndb.StringProperty()
        body = ndb.TextProperty()
        author_key = ndb.KeyProperty()
        author_name = ndb.StringProperty(indexed=False)
    

    This way you have the author name with the blogpost. Otherwise, you'd need to fetch the list of blogposts, then for each blogpost, fetch the Author entity to get the name. That would be much slower, and much more expensive.