Django select_related in reverse

后端 未结 1 1641
故里飘歌
故里飘歌 2021-02-08 12:16

I have the following model:

class Campaign(models.Model):
    some_campaign_field = models.CharField()

class Position(models.Model):
    campaign = models.Forei         


        
1条回答
  •  余生分开走
    2021-02-08 12:58

    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: it should be added this import

    from django.db.models import Prefetch
    

    Ref. Prefetch docs

    0 讨论(0)
提交回复
热议问题