Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Filter based on 2 fields

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?

like image 381
Ryan Tran Avatar asked Mar 23 '26 07:03

Ryan Tran


1 Answers

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 django-3.2 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
)
like image 65
Willem Van Onsem Avatar answered Mar 25 '26 19:03

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!