Hedde van der Heide
Hedde van der Heide

Reputation: 22439

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.

Upvotes: 5

Views: 1055

Answers (1)

Chris Pratt
Chris Pratt

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

Related Questions