﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
23805	query `first` method clears cached queryset for prefetch_related	Aleck Landgraf	nobody	"When a cached queryset is iterated through with `prefetch_related`, if `.first()` is called during the iteration, a new DB query is fired off. This is potentially due to the LIMIT 1 `[:1]` or the `order_by` added to the queryset with the `first` method.

https://github.com/django/django/blob/master/django/db/models/query.py#L518

ex.
{{{
from django.db import connection
connection.queries = []

pizzas = Pizza.objects.all().prefetch_related('toppings')
print len(connection.queries)  # 2

for pizza in pizzas:
    first_topping = pizza.toppings.first()

print len(connection.queries)  # 2 + number of pizzas
}}}

This fixes in my code at least:
{{{
from django.db import connection
connection.queries = []

pizzas = Pizza.objects.all().prefetch_related('toppings')
print len(connection.queries)  # 2

for pizza in pizzas:
    try:
        first_topping = pizza.toppings.all()[0]
    except IndexError:
        first_topping = None

print len(connection.queries)  # 2
}}}"	Uncategorized	closed	Database layer (models, ORM)	dev	Normal	invalid	first query		Unreviewed	0	0	0	0	0	0
