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
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
- [Django]-Django Postgresql syncdb error
- [Django]-Django can not delete csrftoken after logout
- [Django]-Getting task_ids for all tasks created with celery chord
- [Django]-Django Test – South migration reports 'no such table' but I can see said table in the db
- [Django]-Django collectstatic on S3 uploads unchanged files everytime on Heroku
Source:stackexchange.com