Hsn
Hsn

Reputation: 1238

How to get entity keys(parent and custom name) in datastore using python3

I have an entity like this below..

 Name/ID                   Parent                    Rollen               email          first_name      last_name
name=CidassUID  Key(Tenant, 'CidassGroupID')    ["user","admin"]    [email protected]  user first name user last name  

Now for example i would like to query data whose email = [email protected] and get the Entity Key(both id and parent).. what i am doing write now in python is

from google.cloud import datastore
def create_client(project_id):
    return datastore.Client(project_id)
def list_user(client):
    query = client.query(kind='User')
    query.add_filter('email','=','[email protected]')
    l=query.fetch()
    l=list(l)
    print(l)

Now it is giving me the response back as

[<Entity('Tenant', 'CidassGroupID', 'User', 'CidassUID') {'first_name': 'user first name', 'last_name': 'user last name', 'email': '[email protected]', 'Rollen': ['user', 'admin']}>]

and if i convert it to a dictionary

for entity in l:
    a=entity
d=dict(a)
print(d)

it shows the ouptut like this and remove the Entity..

{'first_name': 'user first name', 'last_name': 'user last name', 'email': '[email protected]', 'Rollen': ['user', 'admin']}

How can i get the Entity keys e.g. ('Tenant', 'CidassGroupID') ('User', 'CidassUID') from this response?

thanks a lot!

Upvotes: 0

Views: 607

Answers (1)

Ed Ward
Ed Ward

Reputation: 2331

This seems to work... I haven't tested it with the actual google api, but it should function the same...

d = dict(l[0])
keys = l[0].key.flat_path

new = {keys[i]:keys[i+1] for i in range(0, len(keys), 2)}
d.update(new)

print(d)

Output:

{'first_name': 'user first name', 'last_name': 'user last name', 'email': '[email protected]', 'Rollen': ['user', 'admin'], 'Tenant': 'CidassGroupID', 'User': 'CidassUID'}

Upvotes: 1

Related Questions