Django many to many annotations and filters
Posted
by
dl8
on Stack Overflow
See other posts from Stack Overflow
or by dl8
Published on 2013-10-29T03:32:11Z
Indexed on
2013/10/29
3:54 UTC
Read the original article
Hit count: 375
So I have two models, Person and Film where they're in a many to many relationship. My goal is to grab a film, and output the persons that have also appeared in at least 10 films.
For example I can get the count individually by:
>>> Person.objects.get(short__istartswith = "Matt Damon").film_set.count()
71
However, if I try to filter all the actors of a particular film out:
>>> Film.objects.get(name__istartswith="Saving Private Ryan").actors.all().annotate(film_count=Count('film')).filter(film_count__gte=10)
[]
it returns an empty set since if I manually look at everyone's film_count it's 1, even though an actor such as Matt Damon (as seen above) has been in 71 films in my db.
As you can see with this query, the annotation doesn't work:
>>> Film.objects.get(name__istartswith="Saving Private Ryan").actors.all().annotate(film_count=Count('film'))[0].film_count
1
>>> Film.objects.get(name__istartswith="Saving Private Ryan").actors.all().annotate(film_count=Count('film'))[0].film_set.count()
7
and I can't seem to figure out a way to filter it by the film_set.count()
© Stack Overflow or respective owner