Skip to content

Commit

Permalink
Fix crash when filtering on implicit pk field on abstract model (#1328
Browse files Browse the repository at this point in the history
)

Avoid crashing when queryset filters on an implicit pk field for a model, when model is abstract.
  • Loading branch information
flaeppe authored Jan 23, 2023
1 parent 7d49ae6 commit d716b49
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
4 changes: 4 additions & 0 deletions mypy_django_plugin/django/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,10 @@ def resolve_lookup_into_field(

def resolve_lookup_expected_type(self, ctx: MethodContext, model_cls: Type[Model], lookup: str) -> MypyType:
query = Query(model_cls)
if lookup == "pk" or lookup.startswith("pk__") and query.get_meta().pk is None:
# Primary key lookup when no primary key field is found, model is presumably
# abstract and we can't say anything about 'pk'.
return AnyType(TypeOfAny.implementation_artifact)
try:
lookup_parts, field_parts, is_expression = query.solve_lookup_type(lookup)
if is_expression:
Expand Down
9 changes: 9 additions & 0 deletions tests/typecheck/models/test_abstract.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
- case: test_filter_on_abstract_user_pk
main: |
from django.contrib.auth.models import AbstractUser
AbstractUser.objects.get(pk=1)
AbstractUser.objects.get(pk__in=[1])
reveal_type(AbstractUser().pk) # N: Revealed type is "Any"
AbstractUser.objects.get(pkey=1) # ER: Cannot resolve keyword 'pkey' into field..*
installed_apps:
- django.contrib.auth

0 comments on commit d716b49

Please sign in to comment.