python - Django case when else in filter

标签 python django filter orm case

我需要与此 SQL 类似的代码:

SELECT * FROM tab WHERE a = CASE WHEN x IS NULL THEN b ELSE c END

我的尝试,但没有成功:

model.objects.filter(a=Q(Case(When(x__isnull=True, then='b'), default='c')))

当我尝试运行时,出现此错误:

Traceback (most recent call last):
  File "<input>", line 2, in <module>
  File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query.py", line 904, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1340, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1371, in _add_q
    check_filterable=check_filterable,
  File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1249, in build_filter
    value = self.resolve_lookup_value(value, can_reuse, allow_joins, simple_col)
  File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1058, in resolve_lookup_value
    value = value.resolve_expression(self, **kwargs)
  File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query_utils.py", line 95, in resolve_expression
    check_filterable=False,
  File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1371, in _add_q
    check_filterable=check_filterable,
  File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1237, in build_filter
    arg, value = filter_expr
TypeError: cannot unpack non-iterable Case object

最佳答案

你不应该把它包装在一个 Q 对象中,因为一个 Q 对象是一个条件,一个 Case 不是可以被TrueFalse:

from django.db.models import Case, When

model.objects.filter(a=<b>Case(When(x__isnull=True, then='b'), default='c')</b>)

请注意,您可以将 x__isnull=True 替换为简单的 x=None,这会稍微短一些:

from django.db.models import Case, When

model.objects.filter(a=<b>Case(When(x=None</b>, then='b'), default='c'))

关于python - Django case when else in filter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61296448/

相关文章:

python - 如何在 HTML 文档中查找字符串,忽略空格?

python - 如果图例在轴外,则在单击鼠标时注册双事件

CSS:通过数据过滤器属性选择元素

C - 无法设置 pcap 过滤器。功能无法正常工作

Sharepoint:如何过滤文档库 View 以显示子文件夹的内容?

python - 生成位于圆内的网格坐标

python - Pandas 数据读取器引发 AttributeError : module 'pandas.io' has no attribute 'data'

具有自定义方案的 Django URLField

django - 带有客户端更新的异步 View ,用于长时间运行的进程/ View

django - Restangular、Django REST 和关系