Python django 模板 if 或语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19284270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
django template if or statement
提问by Neil Hickman
Basically to make this quick and simple, I'm looking to run an XOR conditional in django template. Before you ask why don't I just do it in the code, this isn't an option.
基本上,为了快速和简单,我希望在 Django 模板中运行 XOR 条件。在你问我为什么不在代码中这样做之前,这不是一个选择。
Basically I need to check if a user is in one of two many-to-many objects.
基本上我需要检查用户是否在两个多对多对象之一中。
req.accepted.all
and
和
req.declined.all
Now they can only be in one or the other (hence the XOR conditional). From the looking around on the docs the only thing I can figure out is the following
现在它们只能在一个或另一个中(因此 XOR 条件)。通过查看文档,我唯一能弄清楚的是以下内容
{% if user.username in req.accepted.all or req.declined.all %}
The problem I'm having here is that if user.username does indeed appear in req.accepted.all then it escapes the conditional but if it's in req.declined.all then it will follow the conditional clause.
我在这里遇到的问题是,如果 user.username 确实出现在 req.accepted.all 中,那么它会转义条件,但如果它在 req.declined.all 中,那么它将遵循条件子句。
Am I missing something here?
我在这里错过了什么吗?
采纳答案by db0
Rephrased answer from the accepted one:
已接受的答案的改写:
To get:
要得到:
{% if A xor B %}
{% if A xor B %}
Do:
做:
{% if A and not B or B and not A %}
{% if A and not B or B and not A %}
It works!
有用!
回答by Peter DeGlopper
and
has higher precedence than or
, so you can just write the decomposed version:
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 %}
For efficiency, using with
to skip reevaluating the querysets:
为了提高效率,使用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 %}