Fix the query count model for a blog feed

Review the AI's codeEasy10 min

Your task

An AI wrote a Django REST Framework view for a blog feed that shows each post's author and tags. The endpoint is slow, and its query count grows with the page size: the N+1 problem, one query for the list and then more for every row. Your team models the query count for each way of loading the relations, to set a query budget in tests.

An assistant wrote count_feed_queries(page_size, use_select_related, use_prefetch_related). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • page_size: how many posts the page shows.
  • use_select_related: true when the queryset uses select_related("author"). The author is a foreign key, a link to one row in another table.
  • use_prefetch_related: true when the queryset uses prefetch_related("tags"). Tags are a many-to-many relation.
  • Return the number of SQL queries the page runs.

Rules the tests check:

  • The page always runs 1 query for the list of posts.
  • When page_size is 0 or less, that is the only query.
  • Otherwise add the cost of the author: 0 queries with use_select_related, else 1 query per post.
  • Then add the cost of the tags: 1 query with use_prefetch_related, else 1 query per post. The tags cost depends only on use_prefetch_related.

Examples

count_feed_queries(page_size: int, use_select_related: bool, use_prefetch_related: bool) -> int
Example 1
Inputcount_feed_queries(50, False, False)
Output101
Example 2
Inputcount_feed_queries(50, True, True)
Output2
Example 3
Inputcount_feed_queries(1, False, False)
Output3