#django #pattern #python
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.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.