Fix the query budget for an order history page

Review the AI's codeEasy10 min

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 with select_related and folds the item count into the same statement with annotate.
  • Return the number of SQL queries the page runs.

Rules the tests check:

  • A negative order_count or related_fields_per_order counts 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_count times related_fields_per_order.

Examples

count_order_page_queries(order_count: int, related_fields_per_order: int, use_select_related: bool) -> int
Example 1
Inputcount_order_page_queries(800, 3, False)
Output2401
Example 2
Inputcount_order_page_queries(800, 3, True)
Output1
Example 3
Inputcount_order_page_queries(3, 3, False)
Output10