[Answered ]-How to query filter self foreign key

1๐Ÿ‘

โœ…

If you filter with sub_service__type=1 you retrieve all Services that have at least one related Service with type=1. But it is thus allowed that there are other related sub-Services 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)))

Leave a comment