【问题标题】:Dictionnary item with `.` in index索引中带有 `.` 的字典项
【发布时间】:2014-06-06 15:16:23
【问题描述】:

我有这个词典

# Views.py

results = {}
# Set content types
results["teams.team"] = []
results["users.userprofile"] = []

for result in sqs:
    content_type = result.content_type() # teams.team , users.userprofile, ... 
    results[content_type].append(result.get_additional_fields()) # get_additional_fields => {title:"" , ... }

如何在 django 模板中显示 team.team 大小?
我试过{{ results.user.userprofile.count }} 但似乎. 出错了。

谢谢

【问题讨论】:

  • 我已经更新了我的答案。希望对你有帮助
  • 你的意思是要获取"teams.team"中的列表长度?
  • 是的,但只在模板中,并且{{ results['users.userprofile'].count 给出Could not parse the remainder 错误

标签: python python-2.7 django-templates django-views


【解决方案1】:

您的字典应该使用: 而不是=,如下所示:

results = {
    "user.userprofile": {
         "title": "the name"
    }
    ...
}

那么你可以这样做:

{{ results['user.userprofile']['title'] }}

回答您更新的问题:

{{ len(results['teams.team']) }}

【讨论】:

  • dictionnay 只是为了人们可以看到数据结构,它不是我的代码中的那样;)
  • @FabienPapet,你是​​什么意思?字典如下:{key:value, key:value}。如果您将字典更改为我的显示方式,它将适用于我的答案。
  • 我同意,我的意思是我没有在我的代码中手动定义字典
  • @FabienPapet,那么您的字典可能格式正确,尝试运行代码,看看它是否有效。
  • @FabienPapet,请查看我对您更新问题的更新答案。您可以修改它以满足您的需要。
猜你喜欢
  • 2019-02-15
  • 1970-01-01
  • 1970-01-01
  • 2021-01-27
  • 1970-01-01
  • 1970-01-01
  • 2022-10-06
  • 2020-04-18
  • 2013-05-28
相关资源
最近更新 更多