Skip to content

Django: ForeignKey("app_label.Model") is unresolved when the target class is not imported, so <fk>_id is missing #5748

Backlog

Description

@dhruvparanjape

Describe the Bug

Since #4115 (fixing #3932), a ForeignKey("app_label.Model") string reference resolves when the target class is defined or imported in the module that declares the field. When the target is not imported there, the reference is not resolved: the relation is typed Any, and the <fk>_id attribute that Django always adds is missing, so every access reports missing-attribute.

Importing the module is not enough; the class name itself has to be in scope. The "app_label.Model" form exists so that a model can reference another app without importing it, often to avoid an import cycle, so this is the case the string form is mostly used for.

Reproduction

# authors/models.py
from django.db import models


class Author(models.Model):
    name = models.CharField(max_length=100)


class Agent(models.Model):
    name = models.CharField(max_length=100)
# books/models.py
from django.db import models

from authors.models import Agent


class Publisher(models.Model):
    name = models.CharField(max_length=100)


class Book(models.Model):
    # Class reference to a model in another app: resolved.
    agent = models.ForeignKey(Agent, on_delete=models.CASCADE)
    # String reference to a model in this module: resolved.
    publisher = models.ForeignKey("Publisher", on_delete=models.CASCADE)
    # String reference to a model in another app whose class is not imported here:
    # not resolved, even though `authors.models` is imported for `Agent`.
    author = models.ForeignKey("authors.Author", on_delete=models.CASCADE)
# repro.py
from typing import reveal_type

from books.models import Book


def show(book: Book) -> None:
    reveal_type(book.agent)  # Agent
    reveal_type(book.agent_id)  # int
    reveal_type(book.publisher)  # Publisher
    reveal_type(book.publisher_id)  # int
    reveal_type(book.author)  # Any, expected Author
    reveal_type(book.author_id)  # Unknown + missing-attribute, expected int
ERROR Object of class `Book` has no attribute `author_id` [missing-attribute]

If books/models.py adds from authors.models import Author, or the same import under if TYPE_CHECKING:, then book.author is Author and book.author_id is int.

Expected

Notes

Versions

pyrefly 1.5.0 (preset = "default"), Django 5.2, django-stubs 6.1.2, Python 3.12.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions