Lukas Šalkauskas
Lukas Šalkauskas

Reputation: 14361

GQL SELECT Sorting

is there any easier way to select & sort by weight ?

fetchCount = 1000
date1 = datetime.datetime.utcnow().date() 
entries = GqlQuery("SELECT * FROM Entry WHERE category = :category and date >= :datetime ORDER BY date, weight DESC", category = category, datetime = date1).fetch(fetchCount)

if entries is not None:
    # Sort entries ( lazy way for now ).
    sort = True
    while sort:
        sort = False
        for i in range(0, len(entries)-1):
            if entries[i].weight < entries[i + 1].weight:
                e = entries[i + 1]
                entries[i + 1] = entries[i]
                entries[i] = e
                sort = True

Upvotes: 1

Views: 2136

Answers (2)

Guido van Rossum
Guido van Rossum

Reputation: 16890

It's a limitation of the datastore that if you use an inequality filter (e.g. date >= :datetime) that must also be your first ordering key. Also, you can only have inequalities on one property per query. So, in your case you have no choice but sorting them in memory. The sorted() call in the other answer is perfect.

Upvotes: 1

Lukas Šalkauskas
Lukas Šalkauskas

Reputation: 14361

solved by:

entries = GqlQuery("SELECT * FROM Entry WHERE category = :category and date > :datetime ORDER BY date, weight DESC", category = category, datetime = date1).fetch(fetchCount)
entries = sorted(entries, key=lambda x: x.weight, reverse=True)

since there is no other way atm....

Upvotes: 3

Related Questions