#37513 new Bug

FETCH_PEERS: a non-null ForeignKey returns None when the related row is missing

Reported by: Akshat Gupta Owned by:
Component: Database layer (models, ORM) Version: 6.1
Severity: Normal Keywords: fetch modes, FETCH_PEERS
Cc: Akshat Gupta Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

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:

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

Change History (0)

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