[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