Mock CTO interview: fixing an /api/orders/ endpoint that runs 400 queries

Mock CTO Interview November 13, 2026 python

You: "It is an N+1 caused by nested serializers.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# ======================================================================
# Q: CTO: "The /api/orders/ endpoint makes 400 queries. How do you fix it?"
#
# You: "It is an N+1 caused by nested serializers. I confirm it with django-
# debug-toolbar or silk. I add select_related for the FKs, Prefetch for the
# items together with their product, annotate for the counts instead of a
# SerializerMethodField that runs a query, and I lock the number of queries with
# a test so the problem does not come back." Chapter 6.
# ======================================================================

def get_queryset(self):
    return (Order.objects
            .filter(company_id=self.request.user.company_id)
            .select_related('customer', 'shipping_address')
            .prefetch_related(Prefetch(
                'items', queryset=OrderItem.objects.select_related('product')))
            .annotate(items_count=Count('items')))

def test_orders_list_query_count(api_client, user, django_assert_max_num_queries):
    OrderFactory.create_batch(50, company=user.company)
    api_client.force_authenticate(user)
    with django_assert_max_num_queries(4):   # constant, regardless of the number of rows
        api_client.get('/api/v1/orders/')