编辑:以下两个片段实际上运行良好,没有错误!这是我代码库中其他地方的错字。
有没有办法编写 ORM 调用,以便我可以获得 ManyToMany 对象的计数注释并 prefetch_related 那些对象?
例如
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
这会引发 AttributeError: 'Movie' object has no attribute 'genre_count',而
movies = Movies.objects.filter()
movies = movies.annotate(genre_count=Count('genre'))
for movie in movies:
genre_count = movie.genre_count
工作正常