基本上为了快速简单,我希望在 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 中,那么它将遵循条件子句。
我错过了什么吗?
最佳答案
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 %}
关于python - django 模板 if 或语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19284270/