Query on Datastore

I want to get key by query. Written in Python, is it allowed to add "dt_client.key" to "query.projection"?

And how to get the key in 'for' statement? 

0 1 323
1 REPLY 1

Yes, you can get the key of an entity by query in Google Cloud Datastore. However, you cannot add the dt_client.key to query.projection because the key is not a property of the entity and therefore cannot be part of the projection.

When you run a query, you receive Entity objects. Each Entity object has a key property that you can use to get the key of the entity.

Here's an example of how you might do this:

from google.cloud import datastore

def list_entities_with_keys():
dt_client = datastore.Client()

query = dt_client.query(kind='YourKind')
query.add_filter('property', '=', 'value')

for entity in query.fetch():
print('Entity:', entity)
print('Key:', entity.key)

In this example, YourKind should be replaced with the kind of entity you're querying, and 'property', '=', 'value' should be replaced with the property and value you're filtering on. This will print out both the entity and its key for each result.

Note that the key of an entity is a special Key object, and you can get the individual parts of the key (the kind, the ID or name, and the ancestor path) by accessing the properties of the Key object.