【问题标题】:How to compare two querysets in Django templating?如何比较 Django 模板中的两个查询集?
【发布时间】:2017-12-16 04:27:22
【问题描述】:

这听起来可能与其他关于使用 zip 和其他选择比较两个查询集的帖子非常相似,但我已经阅读了很多,但没有一个让我知道我可以为我需要的比较做些什么。

首先,我从数据库中获取查询,并且在 HTML 模板中我需要为 select 元素生成一些默认值。使用一个默认值很容易,但是使用 multiple 我遇到了麻烦,因为 Django 模板中没有 break

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

[<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 中的东西不会运行。

有人可以给我一个想法或知道我可以在这种情况下做什么吗?

以下是我想要实现的目标。

【问题讨论】:

  • 我不会提供这个作为答案,因为它不完全符合您的要求,但作为设计选择,我非常考虑将其移至模板标签 (@ 987654322@) 或者只是在您的视图代码中执行它并在模板上下文中提供结果。
  • 如果你真的想在模板中做这个,那就制作你自己的模板过滤器,pfinn.net/custom-django-filter-tutorial.html

标签: python html django for-loop django-templates


【解决方案1】:

试试这个:

views.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)

index.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>

结果:

【讨论】:

  • arg,难怪你提到我的解决方案应该有效。我把自己弄乱了变量名>。
猜你喜欢
  • 2021-01-02
  • 2019-06-04
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 2019-10-25
  • 2023-01-25
  • 2016-02-24
  • 2013-04-10
相关资源
最近更新 更多