[Fixed]-Django select_related in reverse

19👍

Thanks to the suggestions in the comments, I ended up with the following working solution:

open_campaigns = list(Campaign.objects.prefetch_related(
                                       Prefetch('position_set',
                                                queryset=Position.objects.all(),
                                                to_attr='cached_positions'),
                                       Prefetch('cached_positions__trade_set',
                                                to_attr='cached_trades'),
                                       ).filter(exit_datetime__isnull=True))

Edit: this import is also required

from django.db.models import Prefetch

Ref. Prefetch docs

Leave a comment