【问题标题】:How to iterate this dictionary of lists of lists in Django?如何在Django中迭代这个列表列表字典?
【发布时间】:2011-05-09 20:39:40
【问题描述】:

我有以下带有对象列表的字典。

args =  {'Qtag': [
                  [<Question: Question object>, <Tags: Tags object>],
                  [<Question: Question object>, <Tags: Tags object>]
                 ]
        }

在我的views.py中

args=dict(Qtag=Questag)
t=loader.get.template('main.html')
c=Context(args)

在我的 main.html 中,我正在尝试迭代以下方式

{%if Qtag %}
  {% for item_list in Qtag %}
   {% for item in item_list %}
      </h4> <b> Question</b>:{{item.qid}} {{item.title}} </h4><br/>
      </h4> {{item.question}} </h4>
      <button name="tag" type="submit" value="tagname"> {{item.tagname}} </button>
   {% endfor %}
  {% endfor %}
{% endif %}

当我在 main.html 中尝试上述方式时,我在屏幕上显示了 4 次内容。在这里,由 Question 对象列表和 tag 对象列表组成的第一个列表对应一个问题,另一个问题类似,所以在屏幕上我只希望显示两个问题及其对应的标签。我无法正确迭代以获得我需要的东西。关于如何实现这一点的任何想法!!!

谢谢。

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    我不确定 args=dict(Qtag=Questag) 在您的代码中是什么意思(因为我不知道 Questag 是什么)。我也不知道你的标签是否是可迭代的(我假设是这样)。您的 HTML 看起来也有问题(例如,我没有看到开头的 h4)。

    这就是我会做的,以获得与您正在寻找的东西相似的东西。你可以解决这个问题。

    {% if Qtag %}
       {% for question, tags in Qtag %}
         {# First put in the question header #}
         <h4>Question : {{question.qid}} {{question.title}} </h4>
         {# Then the question body #}
         <p>
         {{question.question}}
         </p>
         {# Now a tag list #}
         <ul>
         {% for tag in tags %}
           <li> 
              <button name = "tag" type="submit" value="{{tag.name}}"> 
                {{tag.name}} 
              </button>
           </li>
         {% endfor %}      
         </ul>
       {% endfor %}
    {% endif %}
    

    您最初的解决方案是二次迭代列表(每次外部迭代都在列表上迭代一次),这就是为什么您看到的东西被打印了 4 次。

    【讨论】:

    • 您好,谢谢。我得到了答案。我尝试使用 item.0.qid,即使用 item.0 访问 Question 对象和使用 item.1 访问 Tags 对象,并删除了第二个 for 循环 {% for item in item_list %}。
    猜你喜欢
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    相关资源
    最近更新 更多