[英]Problem with updating only some fields of entities in Google Cloud Datastore
I created an entity in Google Cloud Datastore using Python this way: 我使用Python在Google Cloud Datastore中创建了一个实体,方法是:
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
此后,当我检查实体列表时,我有了一个具有3个属性
id
, property_0
和property_1
的新实体
In another function, I only updated property_2
which I do so this way 在另一个函数中,我只更新了
property_2
,我这样做是这样
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. 在此之后检查实体列表时,我只会看到具有新值的实体的
property_2
。
How can I update only property_1
of the entity while still keeping the other ones? 如何仅更新实体的
property_1
,同时又保留其他property_1
?
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. 如果只想更新实体的某些属性,则不应使用
.update()
方法,该方法将删除未分配任何值的属性。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.