2

我想了解數據存儲區中的一對多關係;但我無法理解當模型包含ReferenceProperty時如何查詢和更新用戶的記錄。說我有這個模型:如何在使用ReferenceProperty時查詢數據存儲?

class User(db.Model): 
    userEmail = db.StringProperty() 
    userScore = db.IntegerProperty(default=0) 

class Comment(db.Model): 
    user = db.ReferenceProperty(User, collection_name="comments") 
    comment = db.StringProperty() 

class Venue(db.Model): 
    user = db.ReferenceProperty(User, collection_name="venues") 
    venue = db.StringProperty() 

如果我理解正確的話,相同的用戶,通過userEmail唯一標識,可以有很多的意見,並可以與許多場所(餐廳等)

現在有關,比方說用戶[email protected]已經在數據庫中,他提交了一個新條目。

Based on this answer我做這樣的事情:

q = User.all() 
q.filter("userEmail =", [email protected]) 
results = q.fetch(1) 
newEntry = results[0] 

但我不明白這是什麼呢!我想要做的是更新commentvenue字段,這些字段在class Commentclass Venue之下。

你能幫我理解這是如何工作的嗎?謝謝。

回答

4

您發佈的片段是這樣做的(見註釋):

q = User.all() # prepare User table for querying 
q.filter("userEmail =", "[email protected]") # apply filter, email lookup 
               - this is a simple where clause 
results = q.fetch(1) # execute the query, apply limit 1 
the_user = results[0] # the results is a list of objects, grab the first one 

這段代碼the_user後,將對應於用戶記錄與電子郵件"[email protected]"的對象。如果您已經設置了參考資產,則可以通過the_user.commentsthe_user.venues訪問其評論和場地。這些有些場地可以進行修改,這樣說:

some_venue = the_user.venues[0] # the first from the list 
some_venue.venue = 'At DC. square' 
db.put(some_venue) # the entry will be updated 

我建議你做的是有很好的例子GAE文檔的一般掃,你會發現它非常有用: http://code.google.com/appengine/docs/python/overview.html

**更新**:添加新場地的用戶,只需創建新的場地,並指定查詢用戶對象作爲會場的用戶屬性:

new_venue = Venue(venue='Jeferson memorial', user=the_user) # careful with the quoting 
db.put(new_venue) 
1

要獲取給定用戶的所有評論,使用用戶的鍵過濾用戶屬性:

comments = Comment.all().filter("user =", user.key()).fetch(50) 

所以,你可以先查找通過電子郵件的用戶,然後利用搜索評論或場所的鍵。

+1

事實上,他沒有這樣做 - 他一旦加載用戶通過電子郵件查詢,可以輕鬆訪問評論與'user.comments`。 – vonPetrushev 2010-11-28 00:05:11

+0

感謝您的回答。我不知道如何找到搜索評論或場地的關鍵。我必須閱讀這意味着什麼。 但是在這種情況下,我想要做的是理解,如何爲用戶添加評論和場地。 如何使用新評論更新用戶的記錄? – Zeynel 2010-11-28 00:12:52

相關問題