Home > Software design >  Django Filter based on 2 fields
Django Filter based on 2 fields

Time:10-08

I have a model where I can set expire_date_1 and expire_date_2. And 2 filters like this.

filter_1 = Q(expire_date_1__isnull=False) & Q(expire_date_1__lte=after_30days) 
filter_2 = Q(expire_date_2__isnull=False) & Q(expire_date_2__lte=after_30days)

I want to filter the model that if expire_date_2 is not null then using filter_2 else use filter_1 I tried it to do with Case and When but I can't filter in a When function, can I?

CodePudding user response:

You can work with Coalesce [Django-doc] to determine what field to use:

from django.db.models import Coalesce

MyModel.objects.alias(
    exp_date=Coalesce('expire_date_2', 'expire_date_1')
).filter(
    exp_date__lte=after_30_days
)

or prior to with .annotate(…):

from django.db.models import Coalesce

MyModel.objects.annotate(
    exp_date=Coalesce('expire_date_2', 'expire_date_1')
).filter(
    exp_date__lte=after_30_days
)
  • Related