python - django 模板 if 或语句

标签 python django if-statement django-templates xor

基本上为了快速简单,我希望在 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/

相关文章:

python - Django 管理站点根据输入自动填充组合框

django - 连接路径(相对路径)位于基本路径组件(完整路径)之外

java - 在这个简单的例子中替代 if 语句

python - 如何在Pandas数据框中的其他列中填充基于新列的值

python - Django哲学: when to include templates and when to have code generate html?

java - 逐一检查球的四个边是否与墙壁相撞的方法

python - 发送没有 "returning"的 HttpResponse(status=200) - 发送到哪里?

python - 使用webdriver、python、beautifulsoup检索动态网站

php - 需要在有 cPanel 的服务器中安装 mysql-devel - `libmysqlclient_16' 未找到

python - 在 Django 1.6 中获取用户配置文件的新方法是什么?