开发者

Dictionary with arrays in django templates

开发者 https://www.devze.com 2023-02-01 03:36 出处:网络
I have dictionary with arrays inside: dicarr = {\'category\': [\'post1\',\'post2\', \'e.g.\'], \'category2\': [\'post1\',\'post2\']}

I have dictionary with arrays inside:

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

Array is filled in one cycle:

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

How can i get access to array from django template? I tried:

{% for arrdic in dicarr %}
    {{ arrdic.name }}
        {% for i in arr开发者_如何转开发dic.posts %}
            {{ i.name }}
        {% endfor %}
{% endfor %}

But isn't working.


Assuming you have a foreign key pointing to Category on your Post, you don't even need to do it this complicated. All you need to is pass this to the template:

categories = Category.objects.all()

Then you can iterate like this in the template:

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

You can do this with any foreign key relationships. Hope that answers your question!


Following your original code, your template should be (also see for tag docs):

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

But this isn't the best way to do this, because your view will produce number of queries equal to the number of categories. See my answer to a similar question for a more efficient solutions.

0

精彩评论

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