[Fixed]-Django โ€“ how to get a queryset based on a count of references to foreign field

39๐Ÿ‘

โœ…

Itโ€™s confusing when you say โ€œextractโ€ as in exclude.

The answer is in annotation and aggregation.
http://docs.djangoproject.com/en/dev/topics/db/aggregation/

from django.db.models import Count
Games.objects.annotate(num_players=Count('players')).filter(num_players__gt=10)

4๐Ÿ‘

I think you are looking for annotate โ€“ based on example in docs

q = Game.objects.filter(players__isnull=False).annotate(Count('players'))
q[0].players__count #prints first games players

or to filter by count

q = Game.objects.annotate(num_players=Count('players')).filter(num_players__gt=1)
๐Ÿ‘คJamesO

Leave a comment