简体   繁体   中英

Problem with updating only some fields of entities in Google Cloud Datastore

I created an entity in Google Cloud Datastore using Python this way:

client = datastore.Client()

key = client.key('EntityType', id)
entity = datastore.Entity(key=key)
entity.update({'id': id, 'property_0': value_0, 'property_1': value_1,})

After this, when I check my entities list, I have a new entity with the 3 properties id , property_0 and property_1

In another function, I only updated property_2 which I do so this way

key = client.key('EntityType', id)
entity = datastore.Entity(key=key)
entity.update({'property_1': new_value_1,})

When I check the entities list after this, I only see property_2 of my entity with the new value.

How can I update only property_1 of the entity while still keeping the other ones?

You need to fetch it first

key = client.key('EntityType', id)
entity = client.get(key)
entity.update({'property_2': new_value_2,})

If you just want to update some properties of your entity, you should not use the .update() method, this method removes properties that you do not assign any value. Instead you could manually set the value for the property you want to change, like in the example below:

# We first create the entity with the properties we want by using the update method.
client = datastore.Client()
key = client.key('EntityType', id)
entity = datastore.Entity(key=key)
entity.update({'property_0': 'a_string_value', 'property_1': 123})
client.put(entity)

# Then later we just fetch that entity and change the property we want.
client = datastore.Client()
key = client.key('EntityType', id)
entity = datastore.Entity(key=key)
entity['property_0'] = 'a_different_string_value'
client.put(entity)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM