Handle GenericForeignKey class typeinfo lookup failure. (#597)

This addresses an obscure crash we're getting when defining a GenericForeignKey
subclass on a model.

Not sure how this slipped through type checking since
`helpers.lookup_class_typeinfo -> Optional[TypeInfo]` while
`.get_private_descriptor_type(type_info: TypeInfo)` so this should be a clear
type violation.
This commit is contained in:
Simon Charette
2021-04-21 02:44:41 -04:00
committed by GitHub
parent 3931432b34
commit d4c1ed2ce0
2 changed files with 30 additions and 2 deletions

View File

@@ -198,7 +198,12 @@ class DjangoContext:
# it's generic, so cannot set specific model
field_name = field.name
gfk_info = helpers.lookup_class_typeinfo(api, field.__class__)
gfk_set_type = helpers.get_private_descriptor_type(gfk_info, "_pyi_private_set_type", is_nullable=True)
if gfk_info is None:
gfk_set_type = AnyType(TypeOfAny.unannotated)
else:
gfk_set_type = helpers.get_private_descriptor_type(
gfk_info, "_pyi_private_set_type", is_nullable=True
)
expected_types[field_name] = gfk_set_type
return expected_types

View File

@@ -19,3 +19,26 @@
pass
class Tag(models.Model):
content_object = fields.GenericForeignKey()
- case: generic_foreign_key_subclass_could_point_to_any_model_and_is_always_optional
main: |
from myapp.models import Tag, User
myuser = User()
Tag(content_object=None)
Tag(content_object=myuser)
Tag.objects.create(content_object=None)
Tag.objects.create(content_object=myuser)
reveal_type(Tag().content_object) # N: Revealed type is 'Union[Any, None]'
installed_apps:
- myapp
files:
- path: myapp/__init__.py
- path: myapp/models.py
content: |
from django.db import models
from django.contrib.contenttypes import fields
class User(models.Model):
pass
class Tag(models.Model):
content_object = fields.GenericForeignKey()
# Simulate a GenericForeignKey subclass without type infos.
Tag.content_object.__class__ = type('MyGenericForeignKey', (fields.GenericForeignKey,), {})