Count annotation with prefetch_related

1.8k views Asked by At

Edit: Both of the following snippets actually run fine with no errors! It was a typo elsewhere in my codebase.

Is there a way to write an ORM call such that I can get a count annotation of ManyToMany objects and prefetch_related those objects?

e.g.

movies = Movies.objects.filter()
movies = movies.annotate(genre_count=Count('genre'))
movies = movies.prefetch_related('genre_set')

for movie in movies:
    genres = movie.genre_set.all()
    genre_count = movie.genre_count

This throws AttributeError: 'Movie' object has no attribute 'genre_count', whereas

movies = Movies.objects.filter()
movies = movies.annotate(genre_count=Count('genre'))

for movie in movies:
    genre_count = movie.genre_count

works fine

0

There are 0 answers