pythongoogle-cloud-datastoreapp-engine-ndb

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


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?


Solution

  • 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]