django模板if或statement

Nei*_*man 27 python django if-statement xor django-templates

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

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

req.accepted.all 
Run Code Online (Sandbox Code Playgroud)

req.declined.all
Run Code Online (Sandbox Code Playgroud)

现在他们只能在一个或另一个(因此XOR条件).从浏览文档来看,我唯一可以理解的是以下内容

{% if user.username in req.accepted.all or req.declined.all %}
Run Code Online (Sandbox Code Playgroud)

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

我在这里错过了什么吗?

Pet*_*per 37

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 %}
Run Code Online (Sandbox Code Playgroud)

为了提高效率,使用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 %}
Run Code Online (Sandbox Code Playgroud)


db0*_*db0 9

从被接受的人那里重新回答:

要得到:

{% if A xor B %}

做:

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

有用!