我不确定问题标题是否还可以或是否需要更改,但是我的问题是:
在views.py文件中:
def four(request):
mavared1 = PDivContent.objects.filter(chest='1', divv='1')
mavared2 = PDivContent.objects.filter(chest='1', divv='2')
return render(request, 'four.html', {'mavared1': mavared1, 'mavared2': mavared2})
并在four.html中:
<div id="first">
{% for i in mavared1 %}
<li>{{ i.txt }}</li>
{% endfor %}
</div>
<div id="second">
{% for i in mavared2 %}
<li>{{ i.txt }}</li>
{% endfor %}
</div>
代码的输出是这样的:
(对于mavared1):
red
blue
black
pink
(对于mavared2):
a
b
c
d
我已经在我的views.py函数中手动设置了mavared1和mavared2。现在还可以,只有2个,mavared1和mavared2,但是如果我有50个呢?
我必须这样输入吗?
mavared1 = PDivContent.objects.filter(chest='1', divv='1')
.
.
mavared50 = PDivContent.objects.filter(chest='1', divv='50')
还有其他办法吗?
当然,您不必编写循环并使用数据结构dict
来做到这一点:
def four(request):
divv = [str(i) for i in range(1, 51)]
marvared_dict = {}
for divv in divvs:
marvared_dict[divv] = PDivContent.objects.filter(chest='1', divv=divv)
return render(request, 'four.html', {'marvared_dict': marvared_dict})
four.html
{% for divv, marvareds in marvared_dict.items %}
<div id="{{ divv }}">
{% for i in mavareds %}
<li>{{ i.txt }}</li>
{% endfor %}
</div>
{% endfor %}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句