【问题标题】:Type hinting for Django Model subclassDjango 模型子类的类型提示
【发布时间】:2021-08-29 02:21:31
【问题描述】:

我有 Django 视图的辅助函数,看起来像这样(下面的代码)。它返回 None 或与给定查询匹配的单个对象(例如pk=1)。

from typing import Type, Optional

from django.db.models import Model

def get_or_none(cls: Type[Model], **kwargs) -> Optinal[Model]:
    try:
        return cls.objects.get(**kwargs)
    except cls.DoesNotExist:
        return None

假设我创建了自己的模型(例如Car),并带有自己的字段(例如brandmodel)。当我将 get_or_none 函数的结果分配给变量,然后检索实例字段时,我在 PyCharm 中收到令人讨厌的未解析引用警告。

car1 = get_or_none(Car, pk=1)

if car1 is not None:
    print(car1.brand) # <- Unresolved attribute reference 'brand' for class 'Model'

提示摆脱此警告并获取变量代码完成)的propper类型是什么?

【问题讨论】:

  • 看看this对你有没有帮助。
  • 是的,这有点用,但我忘了在我的问题中提及,我想要完成代码(编辑它),无论如何谢谢

标签: python django pycharm type-hinting


【解决方案1】:

找到this 几乎类似问题的答案。解决办法是在打字时使用TypeVar

from typing import TypeVar, Type, Optional

from django.db.models import Model


T = TypeVar('T', bound=Model)

def get_or_none(cls: Type[T], **kwargs) -> Optional[T]:
    ... # same code

一切正常:没有警告代码完成

【讨论】:

    猜你喜欢
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 2018-02-15
    • 2015-08-05
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    相关资源
    最近更新 更多