37

基本上为了快速简单,我希望在 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 中,那么它将遵循条件子句。

我在这里错过了什么吗?

4

2 回答 2

48

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 %}
于 2013-10-09T23:10:29.213 回答
13

从接受的答案改写答案:

要得到:

{% if A xor B %}

做:

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

有用!

于 2016-12-31T14:27:05.843 回答