代码之家  ›  专栏  ›  技术社区  ›  Tsuna

如何比较Django模板中的两个查询集?

  •  0
  • Tsuna  · 技术社区  · 8 年前

    这听起来可能与其他关于使用 zip

    select 要素有一个默认值很容易,但是 multiple break 在Django模板中。

    假设我有两个从后端返回的查询集:

    [<J: j1>, <J: j2>, <J: j3>, <J: j4>]
    [<J: j2>, <J: j4>]
    

    我尝试过这样的开始,我可以理解它的循环比需要的多,所以我也得到了比需要更多的输出。我试图搜索一些可以打破循环的东西,但我认为在Django模板中无法打破循环。

    <select name="" id="">
        {% for j in all_j %}
            {% for s in all_s %}
                {% if j.id == s.id %}
                    <option value="{{ j.id }}" selected="selected">{{ j.name }}</option>
                {% else %}
                    <option value="{{ j.id }}">{{ j.name }}</option>
                {% endif %}
            {% endfor %}
        {% endfor %}
    </select>
    

    我尝试了其他方法,例如

    <select name="" id="">
        {% for s in all_s %}
            {% if s in all_j %}
                <option value="{{ j.id }}" selected="selected">{{ j.name }}</option>
            {% else %}
                <option value="{{ j.id }}">{{ j.name }}</option>
            {% endif %}
        {% endfor %}
    </select>
    

    然后我想,只有当它是真的时,它才会得到输出 else

    有人能给我一个主意或知道我能在这种情况下做什么吗?

    以下是我努力实现的目标。

    enter image description here

    1 回复  |  直到 8 年前
        1
  •  2
  •   Thiago Rossener    8 年前

    试试这个:

    视图.py

    from django.shortcuts import render
    
    
    def home(request):
        context = {
            'all_s': ['j1', 'j2', 'j3', 'j4'],
            'all_j': ['j2', 'j4']
        }
        return render(request, 'index.html', context)
    

    索引.html

    <html>
    <header>
        <title></title>
    </header>
    <body>
    <select name="bla" id="" multiple style="width: 200px;">
        {% for s in all_s %}
            {% if s in all_j %}
                <option value="{{ s }}" selected="selected">{{ s }}</option>
            {% else %}
                <option value="{{ s }}">{{ s }}</option>
            {% endif %}
        {% endfor %}
    </select>
    </body>
    </html>
    

    enter image description here