【问题标题】:django template if or statementdjango 模板 if 或语句
【发布时间】:2013-10-17 12:49:45
【问题描述】:

基本上为了快速简单,我希望在 django 模板中运行 XOR 条件。在你问我为什么不在代码中这样做之前,这不是一个选项。

基本上我需要检查用户是否在两个多对多对象之一中。

req.accepted.all 

req.declined.all

现在它们只能在一个或另一个中(因此是 XOR 条件)。通过查看文档,我唯一能弄清楚的是以下内容

{% if user.username in req.accepted.all or req.declined.all %}

我在这里遇到的问题是,如果 user.username 确实出现在 req.accepted.all 中,那么它会转义条件,但如果它在 req.declined.all 中,那么它将遵循条件子句。

我错过了什么吗?

【问题讨论】:

    标签: python django if-statement django-templates xor


    【解决方案1】:

    and 的优先级高于or,所以你可以只写分解后的版本:

    {% if user.username in req.accepted.all and user.username not in req.declined.all or
          user.username not in req.accepted.all and user.username in req.declined.all %}
    

    为了提高效率,使用with 跳过重新评估查询集:

    {% with accepted=req.accepted.all declined=req.declined.all username=user.username %}
        {% if username in accepted and username not in declined or
              username not in accepted and username in declined %}
        ...
    {% endif %}
    {% endwith %}
    

    【讨论】:

    • 有趣,感谢有关 with 语句的提示,但是由于某种原因,此条件不会接受其中的 else 语句。一直要求 {% endwith %}
    • 您正确地嵌套了它们,对吧?它必须是{% with %} {% if %} {% else %} {% endif %} {% endwith %}
    • 我看不出有什么问题 - 你使用的是哪个版本的 Django?
    • 嗯。我在我的回答中发现一个不一致之处 - 尝试使用 and username not in declined 而不是 and not username in declined。不过,我怀疑这会导致模板标签错误。没有with 可以正常工作吗?
    • 以什么方式失败?该表达式在逻辑上等价于异或。如果我不得不猜测,我会检查 username 是否真的是与 ManyToMany 字段进行比较的正确值,但如果没有看到模型我就无法确定,所以我只是复制了你的非工作版了。我怀疑你可能想检查user in accepted等。
    【解决方案2】:

    已接受答案的改写:

    获得:

    {% if A xor B %}

    做:

    {% if A and not B or B and not A %}

    有效!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 2017-07-20
      • 2015-05-14
      • 2021-06-30
      • 2020-08-09
      • 2014-11-21
      相关资源
      最近更新 更多