How to filter children based parent in django

I have it

from django.db import models class Kid(models.Model): name = models.CharField(max_length=200) class Toy(models.Model): name = models.CharField(max_length=200) owner = models.ForeignKey(Kid) 

I have this request

kids = Kid.objects.all()

Now I want to filter out children who have whole toys named star in it

and I can’t decide which filter to apply

kids.filter(toys_set__icontains='star')

+6
source share
1 answer
 Kid.objects.distinct().filter(toy__name__icontains='star') 

Pay attention to the distinct() method. This is necessary because the child may have several "star" toys, so without distinct() you will get duplicates in the query set.

If you want to filter children by the number of toys found when using aggregation :

 Kid.objects.distinct().filter(toy__name__icontains='star') \ .annotate(toys_num=Count('toy')).filter(toys_num__gt=4) 
+7
source

Source: https://habr.com/ru/post/981327/


All Articles