0

這裏是我的數據模型:谷歌應用程序引擎:查詢的實體沒有URL參數

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

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

我目前在我的主頁(「/」),我想:

  • 查詢所有BlogPost實體的列表,並且
  • 查詢其各自的作者將與BlogPost實體一起顯示。

我可以查詢所有相關博客文章僅僅是這樣的:

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

的Jinja2的模板的index.html是這樣的:

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

所以,我想知道我怎麼能顯示與每個BlogPost實體關聯的Author實體。

謝謝。

回答

1

做到這將是進行非規範化的數據和存儲作者姓名的副本在博客帖子的最佳方式:

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

這種方式,你有博客帖子的作者姓名。否則,您需要獲取blogpost列表,然後爲每個blogpost獲取Author實體以獲取名稱。這會慢得多,而且要貴得多。

+0

感謝您的回答,@dragonx。這個解決方案似乎有很多挑戰。如果我在作者實體內有更多的屬性會怎麼樣?當然,我不能在BlogPost類中包含這些副本。此外,在編輯作者實體時,似乎我還需要檢索與所述作者關聯的所有BlogPost實體,並在其中編輯其字段。 – puoyaahhh

1
{{p's AUTHOR TO BE DISPLAYED HERE. Example: p.author.get.name, p.author.get.fav_colour}}  

只需謹慎一點,每做一次作者調查就會做一次2 ndb rpc調用,並會影響性能。
您可以使用memcache將作者實體存儲在memcache中,或將作者信息非規範化並將其存儲在post實體中。

+0

謝謝你的提醒,@Sandeep。我沒有意識到這一點;我其實有更多的ndb電話。我對數據非規範化非常陌生,這是我剛剛開始閱讀的一個主題。您是否可以發送一些鏈接,讓我可以在GAE上更多地瞭解反規範化如何工作或如何開始? – puoyaahhh

+1

Google開發者團隊擁有良好的視頻資源。您可以在下面的鏈接中找到視頻集合https://developers.google.com/appengine/docs/videoresources 如果解決了您的問題,則可以接受該答案。 – Sandeep

0

下面就來查詢每個作者的方式:

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

    def get_author_async(self): 
     self._author_fetch = author_key.get_async() 

    @property 
    def author_name(self): 
     author = self_author_fetch.get_result() 
     return author.name if author else "" 


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

所以,是的,這是比較容易了前面,但假設你的博客的應用程序是最喜歡的博客,其中每個崗位是編輯的次數屈指可數,而觀看1000倍多次,這是一個昂貴的方式。

相關問題