Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter model on reverse_set length

Consider these pseudo classes:

class Foo(models.Model):
    pass

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

I would like to filter via Foo's manager effectively to get a QuerySet that only holds Foo objects with atleast 2 Bar objects pointing towards it.

like image 759
Hedde van der Heide Avatar asked Jul 30 '12 16:07

Hedde van der Heide


1 Answers

Use aggregation with Count:

from django.db.models import Count

Foo.objects.annotate(bar_count=Count('bar')).filter(bar_count__gte=2)
like image 178
Chris Pratt Avatar answered Sep 28 '22 10:09

Chris Pratt