2011-11-02 61 views
0

與關鍵讀書,我在谷歌應用程序引擎Python的 - 在App Engine中

有一個Python程序當發現在數據存儲中的對象時,我有鑰匙作爲一個字符串,我該怎麼辦直接讀取。下面是我的代碼正在執行一個循環,不好.....

class Opportunity(db.Model): 
    customer = db.ReferenceProperty(Customer,collection_name='opportunitys') 
    BNusername = db.StringProperty() 
    opportunity_no = db.StringProperty() 
    # etc etc etc..... 

#BnPresets holds the object key as a string 

opportunitys = Opportunity.all() 
opportunitys.filter('BNusername =',BnPresets.myusername) 
for oprec in opportunitys: 
    if str(oprec.key()) == BnPresets.recordkey: 
     opportunity = oprec 
     # I have the object here and can process etc etc 

回答

4

您可以從字符串通過將其傳遞直接到構造函數實例db.Key

opportunity_key = db.Key(BnPresets.recordkey) 

一旦你的,只是db.get獲得通過此鍵標識的實體:您還需要驗證OB的用戶名

opportunity = db.get(opportunity_key) 

我想(通過看你使用查詢) ject你得到:

if opportunity.BNusername == BnPresets.myusername 
    process_opportunity(opportunity) 

這應該是非常多的。底線是您應該首先使用密鑰 - 因爲它唯一標識您的實體 - 而不是查詢其他屬性並遍歷結果。

+0

我猜測opportunity = db.get(opportunity_key)進入類Opportunity(db.Model):部分。這意味着當我執行db.get時,我總是使用相同的變量來保存KEY。我還假設機會= Opportunity.all()等代碼將工作,當我想獲得幾個對象。我有這個權利嗎? –

+2

請注意,db.get也將直接在密鑰的字符串表示形式上工作。您可以跳過第一步,然後執行opportunity = db.get(BnPresets.recordkey)。 –