NDB: How to do a partial ancestor match?

user2242238 Source

Context:

I am working on a web app. If I don't use ancestors, trying to update a element after immediately inserting a new value of a ndb.Model does not fetch the new value. Using ancestors though, I get the result consistently.

BUT, I want to make a hierarchy of items.

Example:

class Office(ndb.Expando):
  name = ndb.StringProperty()

Given the offices:

HQ = Office(key=ndb.Key('Office', '0'), name='HQ')
BR1 = Office(key=ndb.Key('Office', '0','Office', 'BR1'), name='Branch 1')
BR2 = Office(key=ndb.Key('Office', '0', 'Office', 'BR2'), name='Branch 2')
BR1S1 = Office(key=ndb.Key('Office', 'S1'), name='Branch 1 Sector 1')
BR1S2 = Office(key=ndb.Key('Office', 'S2'), name='Branch 1 Sector 2')
BR2S1 = Office(key=ndb.Key('Office', 'S1'), name='Branch 2, Sector 1')
BR2S1 = Office(key=ndb.Key('Office', 'S2'), name='Branch 2, Sector 2')

I can't get strong consistency, because they are all root ancestors.

Given the offices:

HQ = Office(key=ndb.Key('Office', '0'), name='HQ')
BR1 = Office(key=ndb.Key('Office', '0','Office', 'BR1'), name='Branch 1')
BR2 = Office(key=ndb.Key('Office', '0', 'Office', 'BR2'), name='Branch 2')
BR1S1 = Office(key=ndb.Key('Office', '0', 'Office', 'BR1','Office', 'S1'), name='Branch 1 Sector 1')
BR1S2 = Office(key=ndb.Key('Office', '0', 'Office', 'BR1','Office', 'S2'), name='Branch 1 Sector 2')
BR2S1 = Office(key=ndb.Key('Office', '0', 'Office', 'BR2','Office', 'S1'), name='Branch 2, Sector 1')
BR2S1 = Office(key=ndb.Key('Office', '0', 'Office', 'BR2','Office', 'S2'), name='Branch 2, Sector 2')

I also can't get them all from a single query, because the ancestor parameter only matches exactly.

I would like to query for the ancestor ndb.Key('Office', '0', *), but haven't figured out how to do it.

Is it possible?

pythongoogle-app-engineapp-engine-ndb

Answers

answered 5 years ago Paul Collingwood #1

See Ancestor Querys

key = ndb.Key(BlogPost, 12345)
qry = Comment.query(ancestor=key)

So your example is

key = ndb.Key(Office, 0)
qry = Office.query(ancestor=key)

comments powered by Disqus