1๐
โ
If you filter with sub_service__type=1
you retrieve all Service
s that have at least one related Service
with type=1
. But it is thus allowed that there are other related sub-Service
s with a different type. The .sub_service
manager will furthermore not filter the queryset of related objects.
You can make use of a Prefetch
object [Django-doc] to filter the relation as well:
from django.db.models import Prefetch
query = Services.objects.filter(
parent_id__isnull=True,sub_service__type=0
).prefetch_related(Prefetch('sub_service', Service.objects.filter(type=0)))
Source:stackexchange.com