Update one property of an entity in google cloud datastore python
Asked Answered
B

3

5

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.

Burberry answered 6/7, 2017 at 13:59 Comment(1)
Check this answer: Duplicate of thisThyrotoxicosis
D
11

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.

Dashpot answered 6/7, 2017 at 14:6 Comment(3)
great thanks, do you know why they decided to call it 'update'? seems like poor naming conventionBurberry
in google.appengine.ext.db and google.appengine.ext.ndb, it's called .put()Eardrop
seems reasonable to write an update_props which does it transactionally to put on your base modelEardrop
E
1

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)
Enterprising answered 28/11, 2017 at 19:10 Comment(2)
This makes no sense to me. Does task[prop] = task[prop] have some kind of side effect to indicate that those properties have been updated??Ingalls
This link seems to imply that just one entry can be updated cloud.google.com/datastore/docs/concepts/…Ingalls
I
0

I think there is some confusion in the documentation. It says you have to update the entire entity, but your code can just update one property of that entity. The following works fine:

with client.transaction():
    key = client.key('Task', 'sample_task')    
    task = client.get(key)    
    task["A"] = contents_of_A
    client.put(task)

As an aside, if you write a class 'bytes' then the property will automatically be assigned as a Blob value, even though Blob value is not available in the drop-down menu

Ingalls answered 9/10, 2022 at 11:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.