Skip to content

Django Support: "pk" field has wrong type when using ForeignKey(…, primary_key=True) #4995

Description

@Feuermurmel

Describe the Bug

In this example, Y's primary key is a foreign key to X:

from django.db.models import DO_NOTHING
from django.db.models import ForeignKey
from django.db.models import Model
from typing_extensions import reveal_type

class X(Model):
    pass

class Y(Model):
    x = ForeignKey(X, DO_NOTHING, primary_key=True)

reveal_type(Y().pk)

Y().pk is resolved as X, but the actual type in this case is int:

$ pyrefly check example.py 
 INFO revealed type: X [reveal-type]
  --> example.py:14:12
   |
14 | reveal_type(Y().pk)
   |            --------
 INFO 0 errors

When a Django model uses a foreign key as primary key, pk contains the "raw value" of the primary key, i.e. the primary key of the referenced model, instead of an instance of the referenced model.

Additional info:

$ python --version
Python 3.13.13
$ pyrefly --version
pyrefly 1.3.1
$ pip list
Package           Version
----------------- ---------------
asgiref           3.12.1
Django            6.1.1
django-stubs      6.1.1
django-stubs-ext  6.1.1
pip               26.1
pyrefly           1.3.1
sqlparse          0.6.0
types-PyYAML      6.0.12.20260906
typing_extensions 4.16.0 

Sandbox Link

No response

(Only applicable for extension issues) IDE Information

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions