From 6a6fd47f285ea464f6a7ee67c4d2161314881d41 Mon Sep 17 00:00:00 2001 From: James Owen Date: Thu, 4 Mar 2021 09:23:13 +0000 Subject: [PATCH] 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. --- django-stubs/db/models/fields/related.pyi | 2 +- tests/typecheck/fields/test_related.yml | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/django-stubs/db/models/fields/related.pyi b/django-stubs/db/models/fields/related.pyi index ae03ea7..053c274 100644 --- a/django-stubs/db/models/fields/related.pyi +++ b/django-stubs/db/models/fields/related.pyi @@ -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]] = ..., diff --git a/tests/typecheck/fields/test_related.yml b/tests/typecheck/fields/test_related.yml index 0a79d19..714242f 100644 --- a/tests/typecheck/fields/test_related.yml +++ b/tests/typecheck/fields/test_related.yml @@ -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]]"]