[Django]-Django reverse m2m query

3👍

You can use a Prefetch-object [Django-doc] for that:

from django.db.models import Prefetch

good_ratings = Prefetch(
    'entry_set',
    queryset=Entry.objects.filter(rating__gte=4),
    to_attr='good_ratings'
)

authors = Author.objects.filter(
    joined__year=date.today().year
).prefetch_related(
    good_ratings
)

Now the Author objects in authors will have an extra attribute good_ratings (the value of the to_attr of the Prefetch object) that is a preloaded QuerySet containing the Entrys with a rating greater than or equal to four.

So you can post-process these like:

res = {
    author: set(author.good_ratings)
    for author in authors
}

Although since the Author objects (from this QuerySet, not in general), already carry the attribute, so there is probably not much use anyway.

Leave a comment