Rahul
Rahul

Reputation: 305

Using multiple conditions in Django's Case When expressions

As per the Django documentation, its possible to use multiple conditions with the When clause.

When(
    registered_on__gt=date(2014, 1, 1),
    registered_on__lt=date(2015, 1, 1),
    then='account_type'
)

However, I am unable to use the same when using the Case clause.

Case(
    When(
        registered_on__gt=date(2014, 1, 1),
        registered_on__lt=date(2015, 1, 1), 
        then='account_type'
    ),
    default='default'
)

I end up getting the following error:

TypeError: __init__() got multiple values for keyword argument 'then'

Is there some way I can achieve this? Am I missing something here?

Upvotes: 15

Views: 14250

Answers (2)

Son Chau
Son Chau

Reputation: 681

Maybe Q expression can help. Try this:

Case(
    When(
        Q(registered_on__gt=date(2014, 1, 1)) & Q(registered_on__lt=date(2015, 1, 1)),
        then='account_type'
    ),
    default='default'
)

Upvotes: 27

Cypherius
Cypherius

Reputation: 551

As I see in the Django docs of Case expression, each When expression in the Case class has its own then parameters, and instead of put all the condition in only one parameter When, I think maybe you should extract into 2 When expressions, with 2 separate then parameters, as below:

    Case(
         When(
            registered_on__gt=date(2014, 1, 1),
            then = 'account_type',
         ),
         When(
            registered_on__lt=date(2015, 1, 1),
            then = 'account_type',
         ),
         default='default'
    )

Hope it helps. If anything else is unclear please let me know. Cheer!

Upvotes: 2

Related Questions