Reputation: 2684
Is it possible to query based on the ancestors (parent) of a KeyProperty?
EG, something like the following:
class Foo(ndb.Model):
bar = ndb.KeyProperty()
Foo.query().filter(Foo.bar.parent == some_key)
That is, I want to find all foos which have a bar key where the parent of the bar key is some_key.
I want to avoid having to store the parent of bar
as a separate key property if that is possible. Basically I want to do an ancestor query on the KeyProperty, but couldn't see how you could do that, if it was possible at all.
My current solution is to use a ComputedProperty to extract the parent of bar and store it as a separate field. This works, but it seems unnecessary because I'm already storing the parent key as part of the bar key.
Upvotes: 2
Views: 1495
Reputation: 10163
Yes, this is called an ancestor query:
Foo.query(ancestor=some_key)
UPDATE:
After conversation in the comments, we cleared up the desired result. A query will only work if the property in question is indexed. You could index parents by using a computed property and querying on it's value. Since .parent()
will return a key, this should not be an issue:
class Foo(ndb.Model):
bar = ndb.KeyProperty()
bar_parent = ndb.ComputedProperty(lambda self: self.bar.parent())
Foo.query(Foo.bar_parent == some_key)
Upvotes: 6