Complete worked example
python
from drf_lab import setup
setup()
from django.db import connection
from django.test.utils import CaptureQueriesContext
from rest_framework import serializers
from drf_lab import reset_fixture
from drf_lab.models import Role
class PublicRole(serializers.ModelSerializer):
company = serializers.CharField(source="company.name", read_only=True)
class Meta:
model = Role
fields = ["id", "company"]
def inspect_example(country):
alice, _, _ = reset_fixture()
selected = Role.objects.filter(owner=alice, country=country).order_by("id").select_related("company")
with CaptureQueriesContext(connection) as captured:
rows = list(PublicRole(selected, many=True).data)
return {"rows": rows, "queries": len(captured)}- Reasoning
- Querysets are lazy, so creating one outside the measurement block does not prove that its SQL has run. The test captures the complete data access and compares exact public rows plus the number of executed queries. Two Ukrainian rows can be serialized with one joined query in this fixture. The scope remains owner and country filtered. Optimization must not widen that selection or change emitted fields. A zero-result query still performs one database read; returning an empty list without querying would be a different implementation and should not be confused with a verified selected scope.