Search code examples
djangodjango-querysetprefetch

How to create Prefetch queryset based on parent queryset in django


Here is the scenario, a project model which contains multiple bids.

Class Project(models.Model):
    user = models.ForeignKey()

Class Bid(models.Model):
    project = models.ForeignKey(Project, related_name='bids')

When we are querying projects, we want to prefetch bids for projects.

Project.objects.filter(whatever condition).prefetch_related(
     Prefetch('bids', queryset=Bid.objects.all())
)

Here we only want to fetch the bids that belongs to the filtered projects, but not all the bids, how can we specify that? I am expecting something like

queryset=Bid.objects.filter(project=project?)... 

Thanks.


Solution

  • Project.objects.filter(whatever condition).prefetch_related(
         Prefetch('bids', queryset=Bid.objects.all())
    )
    

    This looks ok. Django will take care of only fetching the related bids for you. Note that you don’t need Prefetch in this case. You could do:

    Project.objects.filter(whatever condition).prefetch_related('bids')
    

    The Prefetch is useful if you want to filter the queryset, for example:

    Project.objects.filter(whatever condition).prefetch_related(
         Prefetch('winning_bids', queryset=Bid.objects.filter(status='WINNING'))
    )