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

Allow single generic param for Field in ForeignKey #2261

Merged
merged 1 commit into from
Jul 16, 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
2 changes: 1 addition & 1 deletion django-stubs/db/models/fields/related.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def resolve_relation(scope_model: type[Model], relation: str | type[Model]) -> s
# __set__ value type
_ST = TypeVar("_ST")
# __get__ return type
_GT = TypeVar("_GT")
_GT = TypeVar("_GT", default=_ST)

class RelatedField(FieldCacheMixin, Field[_ST, _GT]):
one_to_many: bool
Expand Down
55 changes: 55 additions & 0 deletions tests/typecheck/models/test_related_fields.yml
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,58 @@

class Other(models.Model):
field = models.ForeignKey(MyModel, related_name="others", on_delete=models.CASCADE)


- case: test_related_fields_with_two_generic_parameters
main: |
from myapp.models import Address, School, Student
reveal_type(Student().school) # N: Revealed type is "myapp.models.School"
reveal_type(Student().address) # N: Revealed type is "myapp.models.Address"
s = Student()
s.school = School()
s.address = Address()
installed_apps:
- myapp
files:
- path: myapp/__init__.py
- path: myapp/models.py
content: |
from django.db import models

class School(models.Model):
pass

class Address(models.Model):
pass

class Student(models.Model):
school = models.ForeignKey["School","School"](to="School", on_delete=models.CASCADE)
address = models.OneToOneField["Address","Address"](to="Address", on_delete=models.CASCADE)


- case: test_related_fields_with_one_generic_parameter
expect_fail: True
main: |
from myapp.models import Address, School, Student
reveal_type(Student().school) # N: Revealed type is "myapp.models.School"
reveal_type(Student().address) # N: Revealed type is "myapp.models.Address"
s = Student()
s.school = School()
s.address = Address()
installed_apps:
- myapp
files:
- path: myapp/__init__.py
- path: myapp/models.py
content: |
from django.db import models

class School(models.Model):
pass

class Address(models.Model):
pass

class Student(models.Model):
school = models.ForeignKey["School"](to="School", on_delete=models.CASCADE)
address = models.OneToOneField["Address"](to="Address", on_delete=models.CASCADE)
Loading