﻿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
37581	FETCH_PEERS loads wrong values or raises DoesNotExist for deferred inherited fields with distinct primary keys	Cleisson	Cleisson	"When `QuerySet.fetch_mode(FETCH_PEERS)` is combined with `defer()` or `only()` on a multi-table or multiple concrete inheritance model whose primary key differs from an ancestor's primary key, accessing a deferred inherited field queries the ancestor model with the subclass's primary keys.

If unrelated rows in the ancestor table happen to have those IDs, `FETCH_PEERS` silently populates the subclass instances with values from the wrong rows. If no ancestor rows have those IDs, `DeferredAttribute.__get__()` raises `<Child>.DoesNotExist` even though the rows exist.

This is a bug in the Django 6.1 `FETCH_PEERS` feature (#28586, [e097e8a12f21a4e92594830f1ad1942b31916d0f]).

Models (using the multiple inheritance pattern from the model inheritance documentation, plus a subclass with a custom primary key):

{{{#!python
from django.db import models


class Article(models.Model):
    article_id = models.AutoField(primary_key=True)
    headline = models.CharField(max_length=100)


class Book(models.Model):
    book_id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=100)


class BookReview(Book, Article):
    pass


class Place(models.Model):
    name = models.CharField(max_length=100)


class ParkingLot(Place):
    custom_id = models.IntegerField(primary_key=True)
    place = models.OneToOneField(Place, on_delete=models.CASCADE, parent_link=True)
}}}

Reproduction (IDs in comments assume a fresh database):

{{{#!python
from django.db.models import FETCH_ONE, FETCH_PEERS

# 1. Wrong values returned when ancestor IDs collide with subclass PKs
Article.objects.create(headline=""Unrelated 1"")  # article_id = 1
Article.objects.create(headline=""Unrelated 2"")  # article_id = 2
BookReview.objects.create(title=""Book 1"", headline=""Review 1"")  # pk (book_ptr_id) = 1, article_ptr_id = 3
BookReview.objects.create(title=""Book 2"", headline=""Review 2"")  # pk (book_ptr_id) = 2, article_ptr_id = 4

one = list(BookReview.objects.fetch_mode(FETCH_ONE).defer(""headline"").order_by(""pk""))
print([r.headline for r in one])
# ['Review 1', 'Review 2']

peers = list(BookReview.objects.fetch_mode(FETCH_PEERS).defer(""headline"").order_by(""pk""))
print([r.headline for r in peers])
# Observed: ['Unrelated 1', 'Unrelated 2']
# Expected: ['Review 1', 'Review 2']

# 2. Spurious DoesNotExist when no ancestor row matches subclass PKs
ParkingLot.objects.create(custom_id=100, name=""Lot 1"")
ParkingLot.objects.create(custom_id=200, name=""Lot 2"")

lot1, lot2 = ParkingLot.objects.fetch_mode(FETCH_PEERS).defer(""name"").order_by(""pk"")
lot1.name
# Observed: ParkingLot.DoesNotExist: ParkingLot matching query does not exist.
# Expected: 'Lot 1'
}}}

In `django/db/models/query_utils.py`, `DeferredAttribute.fetch_many()` queries `self.field.model._base_manager`:

{{{#!python
value_by_pk = (
    self.field.model._base_manager.using(db)
    .values_list(attname, flat=True)
    .in_bulk([i.pk for i in to_fetch])
)
}}}

For an inherited field, `self.field.model` is the ancestor model, whereas `[i.pk for i in to_fetch]` are subclass primary keys. `DeferredAttribute.fetch_one()` avoids this because `Model.refresh_from_db()` queries `self.__class__._base_manager`.

Using `instances[0].__class__._base_manager` in `fetch_many()` matches `refresh_from_db()` and joins through the subclass's ancestor links in a single query."	Bug	assigned	Database layer (models, ORM)	6.1	Normal		fetch_mode, FETCH_PEERS, defer, multi-table inheritance		Unreviewed	1	0	0	0	0	0
