Opened 100 minutes ago

Last modified 80 minutes ago

#37581 assigned Bug

FETCH_PEERS loads wrong values or raises DoesNotExist for deferred inherited fields with distinct primary keys

Reported by: Cleisson Owned by: Cleisson
Component: Database layer (models, ORM) Version: 6.1
Severity: Normal Keywords: fetch_mode, FETCH_PEERS, defer, multi-table inheritance
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

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):

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):

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:

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.

Change History (1)

Note: See TracTickets for help on using tickets.
Back to Top