Search code examples
pythondjangodjango-ormdjango-filter

Django queryset filter based on number of children


I'm using Django filters in order to do some filtering for my project. I have the following models:

class Foo(models.Model):
    pass

class Bar(models.Model):
    foo = models.ForeignKey(Foo, models.CASCADE)

My query looks like this:

Foo.objects.filter(blah=blah)

I want to narrow this filter by only giving me Foo objects that have at least 5 Bar objects connected with it via FK.

So if I have 3 Foo objects which respectively have 7, 5, and 3 Bar objects that have their id, then only the first two should be in the end queryset. How would I do that so that the evaluated queryset only has the first two objects in memory?

Thanks!


Solution

  • You can annotate the number of Bar objects, and then filter on these:

    from django.db.models import Count
    
    Foo.objects.annotate(
        nbar=Count('bar')
    ).filter(
        blah=blah,
        nbar__gte=5
    )