GCP Datastore NDB: Filter for KindA elements keys that are NOT IN KindB documentId

61 Views Asked by At

Here is my situation: I have two Datastore kind, I need to create a python query for all Data that don't are present in Kind B. In the sample those are: Data 3 and Data 4.

The constraint here is that i need to filter for elements in KindA which have a key that is different from specific KindB property.

Kind A Kind B
Data 1 Data 1
Data 2 Data 2
Data 3
Data 4
Data 5 Data 5

According to documentation, I can create a query in this way:

query = Account.query(Account.userid == 42)

I've tried this:

myquery = KindA.query(KindA.key.id() != KindB.documentId)

But it throws: AttributeError: 'ModelKey' object has no attribute 'id'

I've tried following this stack overflow question: but it seems infeasible because the number of element in kindB is dynamic, and I can't list them all.

Written in english my query would be: filter KindA elements keys that are NOT IN KindB documentId.

Could you help?

2

There are 2 best solutions below

0
NoCommandLine On BEST ANSWER

Try this

# keys_only=True means Return only the keys which is faster
kindB_Ids = [ a.id() for a in KindB.query().fetch(keys_only=True) ]


kindA_Ids = [ a.id() for a in KindA.query().fetch(keys_only=True) ]

# This gives you rows in KindA whose ids are not in KindB
diff = [ ndb.Key(KindA, a) for a in KindA_Ids if a not in kindB_Ids]

1
Girolamo On

According with this post quoted by @SarahRemo in the comments , here is a working solution.

list_of_id = []
entries = KindB.query()
for request in entries:
    list_of_id.append(request.key.id())

keys = [ndb.Key(KindA, unique_id) for unique_id in list_of_id]
objs= ndb.get_multi(keys)