Django 模型的类型注释

Dje*_*ent 22 python django type-annotation

我正在做一个 Django 项目。由于这是一个新项目,我希望使用 python 3.6+ 类型注释对其进行完整注释。我正在尝试注释模型,但我很难找到一种好的方法。

让我们IntegerField以 为例。我看到两个注释它的选择:

# number 1
int_field: int = models.IntegerField()

# number 2
int_field: models.IntegerField = models.IntegerField()
Run Code Online (Sandbox Code Playgroud)

1 在 mypy 中失败:

Incompatible types in assignment (expression has type "IntegerField[<nothing>, <nothing>]", variable has type "int")
Run Code Online (Sandbox Code Playgroud)

编号 2 对 mypy 来说是可以的,但是 IDE 作为 PyCharm 无法解决它,并且经常抱怨使用了错误的类型。

是否有正确注释模型的最佳实践,这将满足 mypy 和 IDE 的要求?

bug*_*bug 27

Django 模型(和其他组件)很难注释,因为它们背后有很多魔法,好消息是一群很酷的开发人员已经为我们完成了艰苦的工作。

django-stubs提供了一组存根和 mypy 插件,它们为 Django 提供静态类型和类型推断。

例如,具有以下模型:

from django.contrib.auth import get_user_model
from django.db import models

User = get_user_model()

class Post(models.Model):
    title = models.CharField(max_length=255)
    pubdate = models.DateTimeField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
Run Code Online (Sandbox Code Playgroud)

mypy 会抱怨说:

demo$ mypy .
demo/models.py:9: error: Need type annotation for 'title'
demo/models.py:10: error: Need type annotation for 'pubdate'
demo/models.py:11: error: Need type annotation for 'author'
Found 3 errors in 1 file (checked 5 source files)
Run Code Online (Sandbox Code Playgroud)

要修复它,安装软件包就足够了

pip install django-stubs
Run Code Online (Sandbox Code Playgroud)

setup.cfg使用以下内容创建一个文件:

[mypy]
plugins =
    mypy_django_plugin.main

strict_optional = True

[mypy.plugins.django-stubs]
django_settings_module = demo.settings
Run Code Online (Sandbox Code Playgroud)

(不要忘记django_settings_module根据您的设置模块进行更新)

完成此操作后,mypy 将能够推断和检查 Django 模型(和其他组件)的注释。

demo$ mypy .
Success: no issues found in 5 source files
Run Code Online (Sandbox Code Playgroud)

下面是一个小视图中的用法示例:

demo$ mypy .
demo/models.py:9: error: Need type annotation for 'title'
demo/models.py:10: error: Need type annotation for 'pubdate'
demo/models.py:11: error: Need type annotation for 'author'
Found 3 errors in 1 file (checked 5 source files)
Run Code Online (Sandbox Code Playgroud)

再一次,mypy 对提供的注释感到满意:

demo$ mypy .
Success: no issues found in 7 source files
Run Code Online (Sandbox Code Playgroud)

同样,还有一个 Django Rest Framework 包:djangorestframework-stubs