36👍
✅
You can use Prefetch
:
Artist.objects.prefetch_related(Prefetch('release_groups', queryset=ReleaseGroup.objects.order_by('release_date')))
To avoid collision with the name, you can set to_attr
to a different name:
Artist.objects.prefetch_related(Prefetch('release_groups', queryset=ReleaseGroup.objects.order_by('release_date'), to_attr='rgs')).all()
You can then access each cached release group in the template like so:
artist.rgs.0.title
Source:stackexchange.com