[Answered ]-How to filter/annotate prefetched objects in django (more efficiently)?

1👍

You can work with an Exists subquery [Django-doc], so:

from django.db.models import Exists, OuterRef

queryset = Song.objects.filter(
    Exists(Harmony.objects.filter(someQuery, song_id=OuterRef('pk')))
)

Here the song_id=… is the ForeignKey from Harmony to song, so that might be slightly different.

Leave a comment