Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 734
acw Avatar asked Oct 15 '25 04:10

acw


1 Answers

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
)
like image 91
Willem Van Onsem Avatar answered Oct 16 '25 17:10

Willem Van Onsem