How to create dynamic fields in Google App Engine expando class?

有些话、适合烂在心里 提交于 2019-12-06 05:14:49

问题


I have a db expando class called widget.

I'm passing in a json string and converting it to a dict and then adding it to the datastore.

My question is how can I loop through my dict to create dynamic fields.

widget = Widget.get_by_key_name(key_name)
widget.name = self.request.get('wname')
fields = simplejson.loads(self.request.get('wcontents'))
for k,v in fields.iteritems():
  widget.k = v

This renders "k" as my field name as oppose to the k value in the dict.


回答1:


The syntax widget.k references the attribute k on object widget. To dynamically choose which attribute you set, use the built-in setattr method:

setattr(widget, k, v)

Dynamically setting an attribute like this will create the field on that particular entity.




回答2:


Try:

for k, v in fields.items()


来源:https://stackoverflow.com/questions/4160752/how-to-create-dynamic-fields-in-google-app-engine-expando-class

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