[ 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]
Answer 1
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.
Answer 2
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
Answer 3
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
Answer 4
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.