Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 518
Rahul Avatar asked Jan 02 '18 02:01

Rahul


2 Answers

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'
)
like image 65
Son Chau Avatar answered Oct 13 '22 13:10

Son Chau


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!

like image 27
Cypherius Avatar answered Oct 13 '22 14:10

Cypherius