Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

match Field TypeVar variance in models.fields.related #2292

Merged
merged 1 commit into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions django-stubs/db/models/fields/related.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ RECURSIVE_RELATIONSHIP_CONSTANT: Literal["self"]
def resolve_relation(scope_model: type[Model], relation: str | type[Model]) -> str | type[Model]: ...

# __set__ value type
_ST = TypeVar("_ST")
_ST = TypeVar("_ST", contravariant=True)
# __get__ return type
_GT = TypeVar("_GT", default=_ST)
_GT = TypeVar("_GT", covariant=True, default=_ST)

class RelatedField(FieldCacheMixin, Field[_ST, _GT]):
one_to_many: bool
Expand Down
23 changes: 23 additions & 0 deletions tests/typecheck/fields/test_related.yml
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,29 @@
related_name='books')
publisher2 = models.ForeignKey(to=Publisher, related_name='books2', on_delete=models.CASCADE)

- case: foreign_key_subclass
main: |
from myapp.models import A
reveal_type(A.objects.get().b) # N: Revealed type is "myapp.models.B"
installed_apps:
- myapp
files:
- path: myapp/__init__.py
- path: myapp/models.py
content: |
from typing import TypeVar
from django.db import models

_ST = TypeVar("_ST", contravariant=True)
_GT = TypeVar("_GT", covariant=True)

class MyForeignKey(models.ForeignKey[_ST, _GT]): ...

class B(models.Model): ...

class A(models.Model):
b = models.ForeignKey(B, on_delete=models.CASCADE)

- case: to_parameter_as_string_with_application_name__model_imported
main: |
from myapp2.models import Book
Expand Down
Loading