Complete worked example
python
from drf_lab import setup
setup()
from rest_framework import generics, serializers
from rest_framework.test import APIRequestFactory
from drf_lab import reset_fixture
from drf_lab.models import Role
class PublicRole(serializers.ModelSerializer):
class Meta:
model = Role
fields = ["id", "title", "country"]
class RoleList(generics.ListAPIView):
serializer_class = PublicRole
def get_queryset(self):
return Role.objects.filter(owner__username="alice", country=self.request.query_params.get("country", "UA")).order_by("id")
def inspect_example(payload):
reset_fixture()
factory = APIRequestFactory()
request = getattr(factory, payload.get("method", "get"))("/roles/", {"country": payload.get("country", "UA")})
response = RoleList.as_view()(request)
body = {"error": response.data["detail"].code} if response.status_code >= 400 else list(response.data)
return {"status": response.status_code, "body": body}- Reasoning
- get_queryset runs for the request and applies owner and country predicates before ordering. The view serializes that selected collection with the declared serializer. The test sees only id, title and country, making both row selection and field projection observable. A generic view can derive behavior from a class queryset, but avoid evaluating and reusing a cached result accidentally. Request-specific selection belongs in get_queryset. A production user context must come from verified authentication; the hard-coded principal is an explicit fixture simplification.