Reputation: 22439
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.
Upvotes: 5
Views: 1055
Reputation: 239320
Use aggregation with Count
:
from django.db.models import Count
Foo.objects.annotate(bar_count=Count('bar')).filter(bar_count__gte=2)
Upvotes: 11