【问题标题】:Unable to iterate a dictionary in django templating language无法用 django 模板语言迭代字典
【发布时间】:2020-09-21 16:47:42
【问题描述】:

我无法在 views.py where

生成的嵌套字典中迭代(键和值)

context = { "orders_current": orders_current }

返回渲染(请求,“orders/cart.html”,上下文) orders_currentviews.py 中的查询结果:

orders_current = Orders.objects.values('def', 'abc', 'toppings')

'toppings' 作为 JSON 数据存储在数据库中,但在类方法中转换(加载)回字典:

def __str__(self)

models.py 中。我这样做是因为我在某处读到这是在 postgresql 中存储字典的推荐方式。

请注意,orders_current 有多个嵌套字典,例如:

字典 {{ order.toppings }} 传递给 html,cart.html 显示为具有值(逐字),例如:

{“蘑菇”:1.5,“加拿大培根”:1.5}

所以我最近从字典中提取顶部名称和相应价格(键、值)的尝试是:

{% for order in orders_current %}
...
<table>
  {% for name, price in order.toppings.items %}
      <tr>
          <td>{{ name }}:</td>                
          <td>${{ price }}</td>
      </tr>
  {% endfor %}
</table>

我从这段代码 sn-p 中没有得到任何值(名称、价格)。 根据我的网络搜索,我尝试了上述几乎所有变体,并使用不同的方式设置 context 进行传输。任何帮助将不胜感激。

【问题讨论】:

  • 您声称的值是在客户端或服务器中逐字打印的吗?如果是服务器,你可以在前端 console.log 并发布输出吗?
  • 它来自客户端(chrome)浏览器。我在 cart.html 中插入了 {{ order.toppings }}
  • 你可以试试 order.toppings.items.all 和 order.toppings
  • 我试过 order.toppings 但没有用。没有详尽的研究,正如 joezeppe 指出的那样,我认为主要问题是 order.toppings 是字符串而不是字典。一个有趣的观察是 order.toppings 包含 " 而不是 ' 作为字典。

标签: django django-models django-views django-templates


【解决方案1】:

根据您的查询集:

< QuerySet [{'category_name': 'Regular Pizza', 'size': 'small', 'item_name': 'Cheese', 'item_price': Decimal('12.70'), 'toppings_selected': True, 'toppings': '{"Mushrooms": 1.5, "Canadian Bacon": 1.5}'}] >

order.toppings 是一个字符串,尝试在视图中将其转换为字典:

import ast 
for order in orders_current:
     order["toppings"] = ast.literal_eval(order["toppings"])

以下是将字符串字典转换为字典的不同方法。 https://www.geeksforgeeks.org/python-convert-string-dictionary-to-dictionary/

转换后,它应该可以在模板中使用。

【讨论】:

  • 成功了!非常感谢您快速而正确的回复。附注:我需要添加一个 try 子句来传递空值。
猜你喜欢
  • 2012-07-27
  • 2018-11-09
  • 2021-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-05
相关资源
最近更新 更多