【问题标题】:Dictionary with arrays in django templatesdjango模板中带有数组的字典
【发布时间】:2010-12-27 20:20:05
【问题描述】:

我有字典,里面有数组:

dicarr = {'category': ['post1','post2', 'e.g.'], 'category2': ['post1','post2']}

数组填充一个循环:

dicarr = {}
for category in Categories.objects.all():
    category_posts = Post.objects.filter(category=category)
    dicarr[category] = [post for post in category_posts ]

如何从 django 模板访问数组?我试过了:

{% for arrdic in dicarr %}
    {{ arrdic.name }}
        {% for i in arrdic.posts %}
            {{ i.name }}
        {% endfor %}
{% endfor %}

但不工作。

【问题讨论】:

    标签: django django-templates django-views


    【解决方案1】:

    假设您有一个指向帖子类别的外键,您甚至不需要做这么复杂的事情。您只需将其传递给模板:

    categories = Category.objects.all()
    

    然后你可以在模板中这样迭代:

    {% for category in categories %}
        {{ category.name }}
        {% for post in categories.post_set.all %}
            {{ post.name }}
        {% endfor %}
    {% endfor %}
    

    您可以使用任何外键关系来执行此操作。希望能回答你的问题!

    【讨论】:

    • 感谢您的回复。这行得通,你指出我在 django 知识方面的空白。谢谢=)
    【解决方案2】:

    按照您的原始代码,您的模板应该是(另见for tag docs):

    {% for category, posts in dicarr.items %}
        {{ category.name }}
            {% for post in posts %}
                {{ post.name }}
            {% endfor %}
    {% endfor %}
    

    但这不是最好的方法,因为您的视图会产生与类别数量相等的查询数量。有关更有效的解决方案,请参阅my answer to a similar question

    【讨论】:

      猜你喜欢
      • 2014-10-11
      • 1970-01-01
      • 2014-03-27
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 2019-10-22
      • 2018-05-24
      • 2014-03-04
      相关资源
      最近更新 更多