Complete worked example
python
from bootstrap_lab import django_setup
django_setup(__name__)
from bootstrap_lab import install_models
from django.db import models, connection
from django.test.utils import CaptureQueriesContext
class Role(models.Model):
title = models.CharField(max_length=80)
country = models.CharField(max_length=2)
active = models.BooleanField(default=True)
class Meta:
app_label = "framework_lab"
install_models(Role)
def selected_ids(rows, country):
Role.objects.all().delete()
Role.objects.bulk_create([Role(**row) for row in rows])
queryset = Role.objects.filter(country=country, active=True).order_by("id")
with CaptureQueriesContext(connection) as observed:
ids = [role.id for role in queryset]
again = [role.id for role in queryset]
return {"ids": ids, "same": ids == again, "queries": len(observed)}- Reasoning
- The helper seeds controlled rows and constructs one filtered, ordered queryset. Iterating it once performs the query and populates that queryset’s result cache; iterating the same object again reuses those results.