Trevor Branch
Trevor Branch

Reputation: 149

Python - read with key in App Engine

I have a python program in Google App Engine

When finding an object in the datastore when I have the key as a string, how can I do a direct read. Below is my code which is performing a loop, not good.....

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

Upvotes: 0

Views: 76

Answers (1)

Xion
Xion

Reputation: 22770

You can instantiate db.Key from string by passing it directly to the constructor:

opportunity_key = db.Key(BnPresets.recordkey)

Once you have that, simply db.get to obtain the entity identified by this key:

opportunity = db.get(opportunity_key)

I guess (by looking at the query you use) that you also want to verify the username of the object you got:

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

That should be pretty much it. The bottom line is that you should use the key first - as it uniquely identifies your entity - rather than querying for some other property and iterating through results.

Upvotes: 4

Related Questions