Skip to content

Commit 733822c

Browse files
committed
Add IsNotNone expression
1 parent af978ac commit 733822c

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

psqlextra/expressions.py

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from django.db.models import expressions
1+
from django.db.models import expressions, CharField
22

33

44
class HStoreColumn(expressions.Col):
@@ -141,3 +141,35 @@ def resolve_expression(self, *args, **kwargs):
141141
original_expression.target,
142142
)
143143
return expression
144+
145+
146+
def IsNotNone(*fields, default=None):
147+
"""Selects whichever field is not None, in the specified order.
148+
149+
Arguments:
150+
fields:
151+
The fields to attempt to get a value from,
152+
in order.
153+
154+
default:
155+
The value to return in case all values are None.
156+
157+
Returns:
158+
A Case-When expression that tries each field and
159+
returns the specified default value when all of
160+
them are None.
161+
"""
162+
163+
when_clauses = [
164+
expressions.When(
165+
~expressions.Q(**{field: None}),
166+
then=expressions.F(field)
167+
)
168+
for field in reversed(fields)
169+
]
170+
171+
return expressions.Case(
172+
*when_clauses,
173+
default=expressions.Value(default),
174+
output_field=CharField()
175+
)

0 commit comments

Comments
 (0)