﻿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
37513	FETCH_PEERS: a non-null ForeignKey returns None when the related row is missing	Akshat Gupta		"Split from #37508.

With `FETCH_PEERS`, a non-null foreign key returns `None` when the related row no longer exists. `FETCH_ONE` and `prefetch_related()` both raise an exception instead.

Models:

{{{#!python
from django.db import models


class Author(models.Model):
    name = models.CharField(max_length=100)


class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, models.CASCADE)
}}}

{{{#!python
book1, book2 = Book.objects.fetch_mode(FETCH_PEERS).order_by(""pk"")
Author.objects.filter(pk=book2.author_id).delete()  # e.g. by another request
book2.author
}}}

Results:

{{{
FETCH_PEERS       -> None
FETCH_ONE         -> Author.DoesNotExist: Author matching query does not exist.
prefetch_related  -> Book.author.RelatedObjectDoesNotExist: Book has no author.
}}}

`author` isn't nullable, so `None` breaks the descriptor's contract. Code like `book.author.name` fails with an `AttributeError` on `None` instead of a `DoesNotExist` that callers can catch.

Cause: `ForwardManyToOneDescriptor.__get__()` returns right after `instance._state.fetch_mode.fetch(self, instance)`. That skips the `rel_obj is None and not self.field.null` check that runs on the cached path. `prefetch_related()` takes the cached path, which is why it raises.

Fix: assign the fetched value to `rel_obj` and fall through to the null check. A nullable foreign key would still return `None`, as `prefetch_related()` does.
"	Bug	new	Database layer (models, ORM)	6.1	Normal		fetch modes, FETCH_PEERS	Akshat Gupta	Unreviewed	0	0	0	0	0	0
