[Django]-How to filter a Django QuerySet's related fields' 'all' or 'none'

1👍

I haven’t used this API in a while, but I believe this will get the job done:

from django.db.models import Q

normal_and_alive = Q(cat_type="normal") & ~Q(lives__state__in=["dead", "unknown"])
schroedinger_and_not_dead = Q(cat_type="schroedinger") & ~Q(lives__state="dead")

cats = Cat.objects.filter(normal_and_alive | schroedinger_and_not_dead)

See docs for django’s docs for complex lookups with the Q() object

aside: this will only execute one database query

👤Jiaaro

0👍

cats = Cat.objects.filter(id=-1) # make it an empty queryset

temp = Cat.objects.filter(cat_type='normal')
for one in temp:
    cats |= one.lives.filter(state='alive') # set union

temp = Cat.objects.filter(cat_type='schroedinger')
for one in temp:
    cats |= one.lives.exclude(state='dead')

return cats

new answer:

cats = Cat.objects.filter(id=-1) # make it an empty queryset

temp = Cat.objects.filter(cat_type='normal')
for one in temp:
    if len(one.lives.exclude(state='alive')) == 0:
        cats |= Cat.objects.filter(id=one.id)

temp = Cat.objects.filter(cat_type='schroedinger')
for one in temp:
    if len(one.lives.filter(state='dead')) == 0:
        cats |= Cat.objects.filter(id=one.id)

return cats

Leave a comment