18👍
✅
Kid.objects.distinct().filter(toy__name__icontains='star')
Note the distinct()
method. It is required because kid can have several “star” toys so without distinct()
you will get duplicates in the queryset.
If you want to filter kids by number of found toys when use aggregation:
Kid.objects.distinct().filter(toy__name__icontains='star') \
.annotate(toys_num=Count('toy')).filter(toys_num__gt=4)
Source:stackexchange.com