Search code examples
pythongoogle-app-engineapp-engine-ndbgoogle-cloud-datastore

NDB Model Querying of Key Ids using an array filter


I'm trying to query an NDB model using a list of provided key id strings. The model has string ids that are assigned at creation - for example:

objectKey = MyModel(
    id="123456ABC",
    name="An Object"
    ).put()

Now I can't figure out how to query the NDB key ids with a list filter. Normally you can do the MyModel.property.IN() to query properties:

names = ['An Object', 'Something else', 'etc']

# This query works
query = MyModel.query(MyModel.name.IN(names))

When I try to filter by a list of keys, I can't get it to work:

# This simple get works
object = MyModel.get_by_id("123456ABC")

ids = ["123456ABC", "CBA654321", "etc"]

# These queries DON'T work
query = MyModel.query(MyModel.id.IN(ids))
query = MyModel.query(MyModel.key.id.IN(ids))
query = MyModel.query(MyModel.key.id().IN(ids))
query = MyModel.query(MyModel._properties['id'].IN(ids))
query = MyModel.query(getattr(MyModel, 'id').IN(ids))
...

I always get AttributeError: type object 'MyModel' has no attribute 'id' errors.

I need to be able to filter by a list of IDs, rather than iterate through each ID in the list (which is sometimes long). How do I do it?


Solution

  • The following should work:

    keys = [ndb.Key(MyModel, anid) for anid in ids]
    objs = ndb.get_multi(keys)