mirror of
https://github.com/davidhalter/django-stubs.git
synced 2025-12-14 07:47:09 +08:00
Fix type of <fieldname>_id when using ForeignKey(to_field=) (#1176)
* Fix type of <fieldname>_id when using ForeignKey(to_field=) Previously mypy_django_plugin would always use the field type of target model's primary key, but `to_field` can refer to a different field type. * Fixes * More fixes
This commit is contained in:
@@ -143,6 +143,20 @@ class DjangoContext:
|
||||
return AnyType(TypeOfAny.explicit)
|
||||
return helpers.get_private_descriptor_type(field_info, "_pyi_lookup_exact_type", is_nullable=field.null)
|
||||
|
||||
def get_related_target_field(
|
||||
self, related_model_cls: Type[Model], field: "ForeignKey[Any, Any]"
|
||||
) -> "Optional[Field[Any, Any]]":
|
||||
# ForeginKey only supports one `to_fields` item (ForeignObject supports many)
|
||||
assert len(field.to_fields) == 1
|
||||
to_field_name = field.to_fields[0]
|
||||
if to_field_name:
|
||||
rel_field = related_model_cls._meta.get_field(to_field_name)
|
||||
if not isinstance(rel_field, Field):
|
||||
return None # Not supported
|
||||
return rel_field
|
||||
else:
|
||||
return self.get_primary_key_field(related_model_cls)
|
||||
|
||||
def get_primary_key_field(self, model_cls: Type[Model]) -> "Field[Any, Any]":
|
||||
for field in model_cls._meta.get_fields():
|
||||
if isinstance(field, Field):
|
||||
|
||||
Reference in New Issue
Block a user