GAE Datastore - workaround for updating entity?

一世执手 提交于 2020-02-04 07:34:25

问题


Assume:

class Contacts(db.Model):
  first_name = StringProperty()
  last_name = StringProperty()
  phone_number = PhoneNumberProperty()

new_contact = Contacts(first_name="Homer", last_name="Simpson", phone_number = 1234566)
new_contact.put()

I am new to GAE Datastore, but per GAE Datastore Docs (see below if interested), i can't modify a single property of the entity (eg, phone_number). I have to re-declare all properties, and then put() the new entity. Omitting previously-declared properties from the new entity results in them being declared as None. Is there a workaround for this -- such as manually overriding the key-name generation function -- so the entity maintains the same key?

#

from GAE Datastore Docs: To update an existing entity, modify the attributes of the object, then call the put() method. The object data overwrites the existing entity. The entire object is sent to the datastore with every call to put(). Note: The datastore API does not distinguish between creating a new entity and updating an existing entity. If the object's key represents an entity that exists, calling its put() method overwrites the entity.


回答1:


that's not true. You need to have a way to get the contact you want and you can update just that. Using the keyname is only one way to do it. If you know the ID of filter a query to only get one entity, you can update a field from it and the put() to update it.

You could have something like:

query = Contact.all().filter('first_name', 'john').filter('last_name', 'doe')
for contact in query:
   contact.phone_number = 498340594834
   contact.put()

Note that that code would update any contacts with that name to that phone number. If there is more than one with that name, both are updated. Using a keyname can prevent that but you have to create more complex keys since only the first and last name might colide.



来源:https://stackoverflow.com/questions/5736287/gae-datastore-workaround-for-updating-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!