Skip to content

Commit d37f7f0

Browse files
match Field TypeVar variance in models.fields.related (#23)
Co-authored-by: Anthony Sottile <[email protected]>
1 parent 3726bfb commit d37f7f0

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

django-stubs/db/models/fields/related.pyi

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,9 @@ RECURSIVE_RELATIONSHIP_CONSTANT: Literal["self"]
2727
def resolve_relation(scope_model: type[Model], relation: str | type[Model]) -> str | type[Model]: ...
2828

2929
# __set__ value type
30-
_ST = TypeVar("_ST")
30+
_ST = TypeVar("_ST", contravariant=True)
3131
# __get__ return type
32-
_GT = TypeVar("_GT")
32+
_GT = TypeVar("_GT", covariant=True)
3333

3434
class RelatedField(FieldCacheMixin, Field[_ST, _GT]):
3535
one_to_many: bool

tests/typecheck/fields/test_related.yml

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,29 @@
8686
related_name='books')
8787
publisher2 = models.ForeignKey(to=Publisher, related_name='books2', on_delete=models.CASCADE)
8888
89+
- case: foreign_key_subclass
90+
main: |
91+
from myapp.models import A
92+
reveal_type(A.objects.get().b) # N: Revealed type is "myapp.models.B"
93+
installed_apps:
94+
- myapp
95+
files:
96+
- path: myapp/__init__.py
97+
- path: myapp/models.py
98+
content: |
99+
from typing import TypeVar
100+
from django.db import models
101+
102+
_ST = TypeVar("_ST", contravariant=True)
103+
_GT = TypeVar("_GT", covariant=True)
104+
105+
class MyForeignKey(models.ForeignKey[_ST, _GT]): ...
106+
107+
class B(models.Model): ...
108+
109+
class A(models.Model):
110+
b = models.ForeignKey(B, on_delete=models.CASCADE)
111+
89112
- case: to_parameter_as_string_with_application_name__model_imported
90113
main: |
91114
from myapp2.models import Book

0 commit comments

Comments
 (0)