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:
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.
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.