开发者

Convert string "list" to an object

How would you convert this to an object that you can iterate through

[{u'开发者_如何学运维pk': u'1', u'quantity': u'2', u'name': u'3mm aliminum sheet', u'size': u'300x322'},{u'pk': u'2', u'quantity': u'1', u'name': u'2mm aliminum sheet', u'size': u'300x322'}]

This data is saved as above in a CharField() in my Django model. Now I need to iterate it in the template.


Don't do that. Use a JSONField - for an example implementation see here - and store the content as valid JSON, rather than a stringified dict.


s = "[{u'pk': u'1', u'quantity': u'2', u'name': u'3mm aliminum sheet', u'size': u'300x322'},{u'pk': u'2', u'quantity': u'1', u'name': u'2mm aliminum sheet', u'size': u'300x322'}]"
d = eval(s)
print type(d)

This is not a good way of persisting objects. Try to save them using model class.


Update I am updating my answer. But You should write your question clearly. In your question you even not try to show it as a strings. On first look it looks like a list.

You can use http://docs.python.org/dev/library/ast.html python ast module.

In [12]: import ast

In [13]: s = "[{u'pk': u'1', u'quantity': u'2', u'name': u'3mm aliminum sheet', u'size': u'300x322'},{u'pk': u'2', u'quantity': u'1', u'name': u'2mm aliminum sheet', u'size': u'300x322'}]"

In [14]: result = ast.literal_eval(s)

In [15]: result
Out[15]: 
[{u'name': u'3mm aliminum sheet',
  u'pk': u'1',
  u'quantity': u'2',
  u'size': u'300x322'},
 {u'name': u'2mm aliminum sheet',
  u'pk': u'2',
  u'quantity': u'1',
  u'size': u'300x322'}]

In [16]: result[0].get('name')
Out[16]: u'3mm aliminum sheet'

Now you can send this new result value to the template.

{% for r in result.0 %}
       {{ r.name }}
    {% endif %}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜