Fix the query budget for an order history page
Your task
Your Django order history page timed out for a customer with 800 orders. The loop read related fields on each order, and each read ran its own query. That is the N+1 problem: one query for the list, then more for every row. Your tests now set a query budget for the page.
An assistant wrote count_order_page_queries(order_count, related_fields_per_order, use_select_related). It is in the editor. It has a bug. Find it and fix it.
Input and output:
order_count: how many orders the customer has.related_fields_per_order: how many related fields the loop reads on each order. Without preloading, each read is one extra query.use_select_related: true when the queryset preloads the related rows withselect_relatedand folds the item count into the same statement withannotate.- Return the number of SQL queries the page runs.
Rules the tests check:
- A negative
order_countorrelated_fields_per_ordercounts as 0. - The page always runs 1 query for the list of orders, even when the customer has no orders.
- With
use_select_related, that 1 query is all the page runs. - Without it, the page runs 1 query plus
order_counttimesrelated_fields_per_order.
Examples
count_order_page_queries(order_count: int, related_fields_per_order: int, use_select_related: bool) -> intExample 1
Input
count_order_page_queries(800, 3, False)Output
2401Example 2
Input
count_order_page_queries(800, 3, True)Output
1Example 3
Input
count_order_page_queries(3, 3, False)Output
10