简体   繁体   中英

Update one property of an entity in google cloud datastore python

How do I update only one property of an entity in the google cloud datastore, without remove all other properties?

key = client.key('employee', ID)
employee_to_deactivate = datastore.Entity(key)
employee_to_deactivate.update({
    'active':False,
})

this updates the active property to False, but removes all the other properties.

You cannot update specific properties of an entity. All writes (inserts, updates) must include all properties that should be persisted. Whenever you need to do an update, you need to first retrieve the existing entity as a whole, then update one or more properties by setting new values and update the entity.

As mentioned in previous answer, you need to set values to every property you want to keep when updating your entity.

One way to re-use your previous property values when updating a single property, is to iterate over the entity. When using the example code from the datastore documentation , this would look as follows:

with client.transaction():
    key = client.key('Task', 'sample_task')
    task = client.get(key)

    # iterate through the entity to take over all existing property values
    for prop in task:
            task[prop] = task[prop]

    task['done'] = True

    client.put(task)

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