2013-10-09 44 views
21

基本上,爲了使這個快速簡單,我正在尋找在Django模板中運行XOR條件。在你問我爲什麼不在代碼中執行它之前,這不是一個選項。Django模板如果或陳述

基本上我需要檢查用戶是否在兩個多對象之一。

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中,那麼它將遵循條件子句。

我在這裏錯過了什麼嗎?

回答

24

andor更高的優先級,這樣你就可以只寫分解的版本:

{% 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 %} 
+0

有趣的是,感謝關於with語句的提示,但是由於某些原因,這個條件將不會接受其中的else語句。不斷要求{%endwith%} –

+0

你正確地嵌套它們,對吧?它必須是「{%with%} {%if%} {%else%} {%endif%} {%endwith%}'。 –

+0

我已經使用代碼段編輯了我的問題。 –

2

改寫答案從接受一個:

得到:

{% if A xor B %}

務必:

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

它的工作原理!