Skip to content Skip to sidebar Skip to footer

How Do I Use Ndb Keyproperty Properly In This Situation?

I have two models: class User(ndb.Model): email = ndb.StringProperty(required=True) name = ndb.StringProperty(required=True) class Post(ndb.Model): created = ndb.DateT

Solution 1:

If I recall correctly, a KeyProperty will return you a ndb.Key. Once you have the key, it is easy to get the model instance (key.get()). So, in your example, you would:

print post.user.get().name

As far as accessing it in a jinja template -- Sure, it'd just be something like:

{% for post in posts %} 
{{ post.message }}
{{ post.user.get().name }}
{% endfor %}

And yes, this will interact with the datastore once for each key you have. If you'd rather, you can factor it out into one datastore interaction:

keys = [p.user for p in posts]
users = ndb.get_multi(keys)
user_posts = zip(users, posts)

And then in your jinja template:

{% for user, post in user_posts %}
{{ post.message }}
{{ user.name }}
{% endfor %}

Post a Comment for "How Do I Use Ndb Keyproperty Properly In This Situation?"