How do I use ndb KeyProperty properly in this situation?

前端 未结 1 550
北恋
北恋 2021-01-14 05:07

I have two models:

class User(ndb.Model):
    email = ndb.StringProperty(required=True)
    name = ndb.StringProperty(required=True)

class Post(ndb.Model):
         


        
相关标签:
1条回答
  • 2021-01-14 05:22

    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 %}
    
    0 讨论(0)
提交回复
热议问题