2011-11-02 58 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)。 –