[Fixed]-Django advanced query with "or"

1👍

You can try this:

from django.db.models import Q

se_qs = Se.objects\
    .filter(pqse__pq=pq, ws__is_important=True)\
    .exclude(Q(pqse__pqsew__personpqsew__is_valid=False) | 
             Q(pqse__pqsew__personpqsew__isnull=False))

Basically, they idea is to exclude the irrelevant records.
The complexity is in querying the nested relationships. More on this can be read in documentation here

Also, if you want to make it more readable, I would encourage you to look into using related_name for Foreign Keys

Also, relevant documentation on Q objects

Leave a comment