我需要与此 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
不是可以被True
或 False
:
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/