如何在django views.py中的函数中设置许多mysql选择查询

时间:2016-04-14 14:01:24

标签: django

我不确定问题标题是否正确或是否需要更改,但我的问题是:

在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')

还有其他办法吗?!

1 个答案:

答案 0 :(得分:1)

当然不是,你编写循环并使用数据结构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 %}