基本上,为了简单快捷,我希望在Django模板中运行XOR条件.在您问为什么我不在代码中这样做之前,这不是一个选项.

基本上,我需要判断用户是否在两个多对多对象中的一个对象中.

req.accepted.all 

req.declined.all

现在它们只能在一个或另一个中(因此使用XOR条件).从文件的四周看go ,我唯一能想到的是以下几点

{% if user.username in req.accepted.all or req.declined.all %}

我这里遇到的问题是,如果user.username确实出现在req.cepte.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 %}

Django相关问答推荐

Django动态页面.为什么我的代码不工作?

Django mods.py我想要一个函数转到一个变量

django re_path() 函数模式与包含该模式的 url 不匹配

如何从基于类的视图将用户保存在 django 模型中

Django多对多关系报错:<title> object (None)>需要先设置id字段的值.

身份验证有效,但登录无效.一直卡在pending

根据当前对象中的多对多字段过滤对象

过滤查询以获取两个朋友之间的聊天消息?

为什么在 Docker 映像中运行我的 Django 应用程序后下载属性不再起作用?

Django 模板:翻译带有 HTML 的文本块的最佳实践

django REST 框架 - 嵌套 ModelSerializer 的有限查询集?

使用 Django 1.5 实现多种用户类型

带有 Django 和 Python 的 Atlassian Bamboo - 可能吗?

我应该如何在我的模型中使用 DurationField?

如何在 Django 中触发 500 错误?

Celery - 在一台服务器上运行不同的工作人员

如何在 Django 中执行批量插入?

如何在 django 中使用更少的 css?

只使用 Django 的某些部分?

如何更改 ModelForm 中所有 Django 日期字段的默认小部件?