Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can filter parent based on children in django

I have this

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 queryset

kids = Kid.objects.all()

Now I want to filter kids whole toys has name star in it

and I am not able to decide which filter to apply

kids.filter(toys_set__icontains='star')

like image 447
user3214546 Avatar asked Jan 21 '15 05:01

user3214546


People also ask

Can you filter by property Django?

Django-property-filter is an extension to django-filter and provides functionality to filter querysets by class properties. It does so by providing sub-classes for Filters and Filtersets to keep existing django-filter functionality. For more details and examples check the documentation.

What is the purpose of filter () method in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

What is the difference between filter and get method in Django?

Basically use get() when you want to get a single unique object, and filter() when you want to get all objects that match your lookup parameters.


1 Answers

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)
like image 150
catavaran Avatar answered Nov 01 '22 07:11

catavaran