在这种情况下如何正确使用ndb KeyProperty? [英] How do I use ndb KeyProperty properly in this situation?
问题描述
pre $
class User(ndb.Model):
email = ndb.StringProperty required = True)
name = ndb.StringProperty(required = True)
$ b $ class Post(ndb.Model):
created = ndb.DateTimeProperty(auto_now_add = True)
message = ndb.TextProperty(required = True)
user = ndb.KeyProperty(kind = User)
如果我想循环Post模型中的某些帖子。我如何访问用户模型中的名称字段?例如:
对于帖子中的帖子:
print post.message
print post.user.name
所以我猜最后一行是不正确的。我试图搜索,无法弄清楚。并补充一点。有没有办法在Jinja2模板中访问这些信息?
然后最后,我是否正在讨论这个错误?假设有50个职位。我有1个查询来获得这50个职位。访问用户模型上的名称字段将成为每次循环的附加查询?那么51查询如果是这样,是不是更好地使用KeyProperty,只是存储每个职位的用户数据(即使我有更多的数据,如头像,user_id等)?
如果我没有记错, b 是的,这将与数据存储一旦你有每个关键。如果你愿意的话,你可以把它分成一个数据存储交互: I have two models: If I want to loop through some posts in the Post model. How I would access the 'name' field in the User model? For example: So I'm guessing the last line isn't correct. I tried searching and couldn't figure it out. And to add to that. Is there a way to access that info in a Jinja2 template? And then finally, am I going about this wrong? Let's say there are 50 posts. And I have 1 query to get those 50 posts. Is accessing the 'name' field on the User model going to be an additional query for each time it loops? So 51 queries?? If so, is it better to not use KeyProperty and just store the User data with each post (even if I have more data like avatar, user_id, etc)? If I recall correctly, a As far as accessing it in a jinja template -- Sure, it'd just be something like: 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: And then in your jinja template:
这篇关于在这种情况下如何正确使用ndb KeyProperty?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! KeyProperty
会返回一个 ndb.Key
。一旦你有了密钥,很容易获得模型实例( key.get()
)。所以,在你的例子中,你会:
pre $ print post.user.get()。
$至于在jinja模板中访问它 - 当然,它只是像这样的:
$ b
{在帖子中的帖子%}
{{post.message}}
{{post.user.get()。名称}}
{%endfor%}
keys = [p.user ]
users = ndb.get_multi(keys)
user_posts = zip(users,posts)
$ b $然后在你的jinja模板中:
{%user,post_user_posts%}
{ {post.message}}
{{user.name}}
{%endfor%}
class User(ndb.Model):
email = ndb.StringProperty(required=True)
name = ndb.StringProperty(required=True)
class Post(ndb.Model):
created = ndb.DateTimeProperty(auto_now_add=True)
message = ndb.TextProperty(required=True)
user = ndb.KeyProperty(kind=User)
for post in posts:
print post.message
print post.user.name
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
{% for post in posts %}
{{ post.message }}
{{ post.user.get().name }}
{% endfor %}
keys = [p.user for p in posts]
users = ndb.get_multi(keys)
user_posts = zip(users, posts)
{% for user, post in user_posts %}
{{ post.message }}
{{ user.name }}
{% endfor %}