在模板中多次使用压缩查询集 [英] Using zipped queryset many times in template

查看:40
本文介绍了在模板中多次使用压缩查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个只有字符串的模型:

I have a model that is only a string :

class Data(models.Model):
    string = models.CharField(max_length=200);

我的数据库中有 2 个模型的注册实例.

There are 2 registered instances of the model in my database.

此视图呈现此视图,该视图将查询集压缩到另一个列表中:

It is rendered by this view, which zips the queryset which another list:

def index(request):
    data = Data.objects.all();
    data2 = [];
    for x in data:
        data2.append(0);
    return render(request, 'testApp/index.html', {"data": zip(data, data2)})

,这是模板代码:

{% for element, e in data %}
    {{ element.string }} {{ e }} <br/>
{% endfor %}

{% for element, e in data %}
    {{ element.string }} {{ e }} <br/>
{% endfor %}

此模板对数据进行两次迭代,打印出压缩列表中的元素.

This template iterates over the data twice, printing out the elements in the zipped list.

这是我的输出:

hello there 0 
i am a string 0 

我期望有4行输出,因为2个实例被循环了两次.但是,它只打印一次.我在做什么错了?

I am expecting 4 lines of output, because the 2 instances are looped over twice. However it's only printing them out once. What am I doing wrong?

推荐答案

在Python 3中,

In Python 3, zip will give you an iterator, meaning it will be consumed on the first loop and therefore not print anything on the second loop.

您可以通过将迭代器转换为列表来解决此问题,将 zip(data,data2)替换为 list(zip(data,data2)).

You can fix this by casting the iterator to a list, replacing zip(data, data2) with list(zip(data, data2)).

这篇关于在模板中多次使用压缩查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆