Tweak the constructor signature for ManyToManyField (#571)

Prior to this change, ManyToManyField was declared as being generic in
_ST and _GT, but also used the _T Typevar in its __init__ signature.
This caused mypy to add _T to the variables it was generic in when used
as an alias.

The symptom of this problem was that mypy would show an error with the
message "Type application has too few types (3 expected)" where a
ManyToManyField alias was declared, but adding an extra argument would
fail because the type only takes two arguments.

This change brings the signature of ManyToManyField in line with
ForeignKey and OneToOneField.
This commit is contained in:
James Owen
2021-03-04 09:23:13 +00:00
committed by GitHub
parent 54e5ecc16a
commit 6a6fd47f28
2 changed files with 7 additions and 1 deletions

View File

@@ -189,7 +189,7 @@ class ManyToManyField(RelatedField[_ST, _GT]):
swappable: bool = ...
def __init__(
self,
to: Union[Type[_T], str],
to: Union[Type[Model], str],
related_name: Optional[str] = ...,
related_query_name: Optional[str] = ...,
limit_choices_to: Optional[Union[Dict[str, Any], Callable[[], Any], Q]] = ...,

View File

@@ -672,3 +672,9 @@
objects = OrderManager()
user = models.ForeignKey(to=User, on_delete=models.CASCADE, related_name='orders')
- case: many_to_many_field_can_be_used_in_alias
main: |
from typing import TypeVar, Sequence, Union
from django.db import models
T = TypeVar("T", bound=models.Model)
ManyToManyFieldAlias = Union["models.ManyToManyField[Sequence[T], models.manager.RelatedManager[T]]"]