Add properties to Google Datastore entity dynamically

情到浓时终转凉″ 提交于 2020-01-05 04:07:13

问题


I have a below use case:

I have a method that accepts a list of strings. For each of the strings, I need to create a property under an existing google data store entity A

Example: I have an existing entity Person with properties fname and lname. If the input list has strings - address, city, I need to update the entity Person to include these new properties address and city.

I'm coding this use case in Python. Any suggestions on how I can achieve this?


回答1:


So the best way to do this is to let your class inherit ndb.Expando. The difference between Expando and Model is that you can always add attributes to an Expando entity and be able to store it in the Datastore.

Knowing this, there are several ways to proceed, but I am guessing you’re also going to need to use Python’s setattr(object, name, value) method to pass the attribute name from a string.




回答2:


Take a look at the Expando model class: https://cloud.google.com/appengine/docs/standard/python/ndb/creating-entity-models#creating_an_expando_model_class

class Person(ndb.Expando):
    pass

person = Person(fname='some', lname='body')
person_key = person.put()

...

person = person_key.get()
person.city = 'San Francisco'
person.address = '1234 Main St.'
person.put()


来源:https://stackoverflow.com/questions/45570769/add-properties-to-google-datastore-entity-dynamically

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