Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!