django 存根类型提示中foreignKey 的第二个类型参数是什么?

问题描述 投票:0回答:1

我应该在这个片段中的

_GT
类型变量的位置放置什么?

from django.db.models import ForeignKey, PROTECT

order = ForeignKey["ExtensionOrder", _GT](
    "subscriptions.ExtensionOrder",
    null=False,
    on_delete=PROTECT
)

存根在这里:(来源

class ForeignKey(ForeignObject[_ST, _GT]):
    _pyi_private_set_type: Union[Any, Combinable]
    _pyi_private_get_type: Any

    ...
    
    # class access
    @overload  # type: ignore
    def __get__(self, instance: None, owner) -> ForwardManyToOneDescriptor: ...
    # Model instance access
    @overload
    def __get__(self, instance: Model, owner) -> **_GT**: ...
    # non-Model instances
    @overload
    def __get__(self: _F, instance, owner) -> _F: ...

Pylance 对此很抱怨,但我不确定

_GT
应该是什么

python-3.x django type-hinting python-typing pylance
1个回答
0
投票

您需要在

Union
课程中进行
Combinable

但它无法在运行时导入,因此请将其嵌套在
TYPE_CHECKING
检查中。

from typing import TYPE_CHECKING
from django.db.models import ForeignKey, PROTECT
if TYPE_CHECKING:
    from django.db.models import Combinable

order = ForeignKey["ExtensionOrder" | "Combinable" , "ExtensionOrder"](
    "subscriptions.ExtensionOrder",
    null=False,
    on_delete=PROTECT
)
© www.soinside.com 2019 - 2024. All rights reserved.