1👍
✅
You can use a combination of .filter(…)
[Django-doc] and .exclude(…)
[Django-doc] in an Exists
subquery [Django-doc]:
from django.db.models import Exists, OuterRef
Model1.objects.filter(
Exists(
Model2.objects.filter(rel1=OuterRef('pk')).exclude(
rel2=OuterRef('pk')
)
)
)
We thus return Model1
objects given there exists (at least one) Model2
object where that item appears in the rel1
relation, and not in the rel2
relation.
Source:stackexchange.com