Prefetch objects enable Django developers to control the operation of prefetch_related. When we pass in a string argument to prefetch related, we’re saying fetch all of the related objects.

A prefetch object lets us pass in a custom queryset to fetch a subset of the related objects.

tickers_with_prefetch = Ticker.objects.all().prefetch_related(
    models.Prefetch(
        "ticker_prices",
        queryset=TickerPrice.objects.filter(
            models.Q(close_date=today)
            | models.Q(close_date=yesterday)
        ),
    )
)

In this example, we combine a previous query we made for ticker prices from today or yesterday and pass that as the query set of our prefetch object. We fetch all tickers and with them we fetch all related ticker prices from today and yesterday.

Related Posts

  • Using Q Objects for Complex Queries
  • Define Custom Query Sets and Model Managers for Code Reuse
  • Annotate Querysets to Fetch Specific Values
  • Optimize Database Calls with Prefetch Related and Select Related
  • Migrating your Wagtail site to a different database engine