Skip to content

Commit d716b49

Browse files
authored
Fix crash when filtering on implicit pk field on abstract model (#1328)
Avoid crashing when queryset filters on an implicit pk field for a model, when model is abstract.
1 parent 7d49ae6 commit d716b49

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

mypy_django_plugin/django/context.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,10 @@ def resolve_lookup_into_field(
384384

385385
def resolve_lookup_expected_type(self, ctx: MethodContext, model_cls: Type[Model], lookup: str) -> MypyType:
386386
query = Query(model_cls)
387+
if lookup == "pk" or lookup.startswith("pk__") and query.get_meta().pk is None:
388+
# Primary key lookup when no primary key field is found, model is presumably
389+
# abstract and we can't say anything about 'pk'.
390+
return AnyType(TypeOfAny.implementation_artifact)
387391
try:
388392
lookup_parts, field_parts, is_expression = query.solve_lookup_type(lookup)
389393
if is_expression:
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
- case: test_filter_on_abstract_user_pk
2+
main: |
3+
from django.contrib.auth.models import AbstractUser
4+
AbstractUser.objects.get(pk=1)
5+
AbstractUser.objects.get(pk__in=[1])
6+
reveal_type(AbstractUser().pk) # N: Revealed type is "Any"
7+
AbstractUser.objects.get(pkey=1) # ER: Cannot resolve keyword 'pkey' into field..*
8+
installed_apps:
9+
- django.contrib.auth

0 commit comments

Comments
 (0)