2

Rafe Kaplan在數據存儲here中有一對很好的關係。我試圖將其適用於更簡單的UserVenue的情況。所以用戶可以去許多餐館;我要打印的用戶電子郵件和餐館的用戶去:數據存儲中的一對多關係

class User(db.Model): 
    userEmail = db.StringProperty() 

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

class OneToMany(webapp.RequestHandler): 
    def get(self): 
     scott = User(userEmail="[email protected]") 
     scott.put() 
     Venue(user=scott, 
        venue="club1").put() 
     Venue(user=scott, 
        venue="club2").put() 

     for v in scott.venues: 
      self.response.out.write(v.venue) 

這將打印"club1 club2"

但我想"[email protected]"與他去的地方相關聯;所以我想打印是這樣的:"[email protected]: club1, club2"

試圖

for v in scott.venues: 
    self.response.out.write(userEmail) 
    self.response.out.write(v.venue) 

給出了錯誤:

self.response.out.write(userEmail) 
NameError: global name 'userEmail' is not defined 

什麼是這樣做的正確方法是什麼?謝謝!

EDIT2(RE:答案通過vonPetrushev)

這似乎工作:

query = User.all() 
    query.filter("userEmail =", "[email protected]") 
    results=query.fetch(1) 
    scott=results[0] 
    self.response.out.write("%s went to:" % scott.userEmail) 
    for venue in scott.venues: 
     self.response.out.write(venue.venue) 

顯示:

[email protected] went to:club1club22

編輯(RE:答案通過vonPetrushev )

我有點困惑。

所以我想寫這樣

query = User.all() 
query.filter("userEmail =", "[email protected]") 

查詢並顯示與該用戶相關聯的所有場館。

目前還不清楚UserVenue是如何連接的。

回答

1

userEmailfor循環的範圍內不是定義的名稱。你需要的是:

for v in scott.venues: 
    self.response.out.write(scott.userEmail) 
    self.response.out.write(v.venue) 

編輯:關於你的編輯 - 如果你的目標是要連接查詢 - 你不能,不與谷歌應用程序數據存儲。但是,你可以抓住用戶是這樣的:

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

然後拿到場地像scott.venues。該關係在db.ReferenceProperty的行中定義,該行定義什麼是someuser.venues以及什麼是somevenue.user

+0

感謝這項工作和打印:`[email protected] club1 s[email protected] club22`我添加了一個`EDIT`,因爲我不懂如何查詢用戶並獲取所有場地。 – Zeynel 2010-11-27 18:51:16

相關問題