Search code examples
sql-order-bygqllistproperty

Using GQL sort by the count of a ListProperty


If I have an db.Model object such as:

class Foo(db.Model):
    title = db.StringProperty()
    bars = db.ListProperty(db.Key)

and I wanted to query the datastore for all of the Foo entities and sort that set by the Foo objects that have the most bars, how would I write the GQL?

I was hoping for something as simple as:

fooQuery = db.GqlQuery("SELECT * FROM Foo ORDER BY len(bars) DESC"

but that doesn't work...


Solution

  • If you need to do something like that, you'll have to include another IntegerProperty to store the length, and keep it in sync yourself. GQL does not support that query.