class When(condition=None, then=None, **lookups)
[source]
A When()
object is used to encapsulate a condition and its result for use in the conditional expression. Using a When()
object is similar to using the filter()
method. The condition can be specified using field lookups or Q
objects. The result is provided using the then
keyword.
Some examples:
>>> from django.db.models import When, F, Q >>> # String arguments refer to fields; the following two examples are equivalent: >>> When(account_type=Client.GOLD, then='name') >>> When(account_type=Client.GOLD, then=F('name')) >>> # You can use field lookups in the condition >>> from datetime import date >>> When(registered_on__gt=date(2014, 1, 1), ... registered_on__lt=date(2015, 1, 1), ... then='account_type') >>> # Complex conditions can be created using Q objects >>> When(Q(name__startswith="John") | Q(name__startswith="Paul"), ... then='name')
Keep in mind that each of these values can be an expression.
Note
Since the then
keyword argument is reserved for the result of the When()
, there is a potential conflict if a Model
has a field named then
. This can be resolved in two ways:
>>> When(then__exact=0, then=1) >>> When(Q(then=0), then=1)
Please login to continue.