#django #pattern #python

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.

1tickers_with_prefetch = Ticker.objects.all().prefetch_related(
2    models.Prefetch(
3        "ticker_prices",
4        queryset=TickerPrice.objects.filter(
5            models.Q(close_date=today)
6            | models.Q(close_date=yesterday)
7        ),
8    )
9)

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.