Fix the query count model for a blog feed
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 usesselect_related("author"). The author is a foreign key, a link to one row in another table.use_prefetch_related: true when the queryset usesprefetch_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_sizeis 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 onuse_prefetch_related.
Examples
count_feed_queries(page_size: int, use_select_related: bool, use_prefetch_related: bool) -> intExample 1
Input
count_feed_queries(50, False, False)Output
101Example 2
Input
count_feed_queries(50, True, True)Output
2Example 3
Input
count_feed_queries(1, False, False)Output
3