topless
topless

Reputation: 8221

App engine query retrieve data with index reference


class Entry(Base):
    amount = db.IntegerProperty()


entries = Entry.gql("WHERE amount > 0")

Is there a way to refer to entries result with an index as an array, for example

my_entry = entries[4]

Upvotes: 2

Views: 164

Answers (5)

Xion
Xion

Reputation: 22770

If you want to refer to one object of specific index in your result query, you can use the fetch method of db.Query with offset parameter:

entry = Entry.gql("WHERE amount > 0").fetch(1, offset=4)[0]
print entry.amount

However, if you want to refer to the multiple objects from the query results, fetch them all and index as normal Python array:

entries = Entry.gql("WHERE amount > 0").fetch(1000)
print entries[4].amount
print entries[5].amount
print entries[7].amount
# etc.

Upvotes: 1

Drew Sears
Drew Sears

Reputation: 12838

entries = [x for x in Entry.gql("WHERE amount > 0")]

The distinction between this and previous answers is that it filters at the datastore rather than in the handler, and doesn't require you to guess the maximum number of entities that will be returned.

Upvotes: 3

garnertb
garnertb

Reputation: 9584

entries= [entry for entry from Entry.all() if entry.amount > 0]
print entries[4]

Upvotes: -1

Abdul Kader
Abdul Kader

Reputation: 5842

You have to do a fetch() . which will give you a list of entries . In that case my_entry=entries[4] will give you the fifth object. What you were trying to do is manipulating the gql object. Which obviously won't work. Try this

class Entry(Base):
    amount = db.IntegerProperty()


entries = Entry.gql("WHERE amount > 0").fetch(1000)

print entries[4].amount

Upvotes: 1

systempuntoout
systempuntoout

Reputation: 74054

You could use the fetch() method on the Query instance:

class Entry(Base):
    amount = db.IntegerProperty()


entries = Entry.gql("WHERE amount > 0").fetch(5)

print entries[4].amount

Upvotes: 2

Related Questions