Aaron
Aaron

Reputation: 812

How can I retrieve a single record from the Google App Engine Datastore?

Using Google App Engine and GQL and Python:

in my datastore I have something like the following

class Thing(db.Model):
   domain = db.StringProperty(required=True)
   name = db.StringProperty()
   ...more...

and in my handler I have

currentThing = db.GqlQuery("SELECT * FROM Thing WHERE domain=:1 LIMIT 1",
                                       "example.com")

I know this will at MOST return one Thing but I can't seem to find a way to collect that one thing in a Thing object without going through a looping process which seems a bit odd to me.

I've also tried using the Thing.gql("WHERE domain=:1 LIMIT 1", "example.com") syntax to no avail. They all seem to return collections.

I'm coming from a .NET background and am new to Python and App Engine, but I'm looking for something similar to the .FirstOrDefault() functionality.

Upvotes: 2

Views: 2436

Answers (1)

Will McCutchen
Will McCutchen

Reputation: 13117

Just add a .get() onto the end of either of your queries. From the docs:

Executes the query, then returns the first result, or None if the query returned no results.

get() implies a "limit" of 1, and overrides the LIMIT clause of the GQL query, if any. At most 1 result is fetched from the datastore.

See also .fetch(limit, offset=0), which will allow you to retrieve limit results from the query.

Upvotes: 7

Related Questions