Django 模型(和其他组件)很难注释,因为它们背后有很多魔力,好消息是一组很酷的开发者已经为我们做好了艰苦的工作。
Django 存根 https://github.com/typeddjango/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)
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)
要修复它,安装该软件包就足够了
pip install django-stubs
并创建一个setup.cfg
文件包含以下内容:
[mypy]
mypy_path = ./demo
plugins =
mypy_django_plugin.main
strict_optional = True
[mypy.plugins.django-stubs]
django_settings_module = demo.settings
(别忘了更新mypy_path
and django_settings_module
指向您的设置模块的目录,根据您的命名方式)
完成此操作后,mypy 将能够推断和检查 Django 模型(和其他组件)的注释。
demo$ mypy .
Success: no issues found in 5 source files
下面是小视图中的用法示例:
from django.db.models.query import QuerySet
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
from demo.models import Post
def _get_posts() -> 'QuerySet[Post]':
return Post.objects.all()
def posts(request: HttpRequest, template: str='posts.html') -> HttpResponse:
return render(request, template, {'posts': _get_posts()})
mypy 再次对提供的注释感到满意:
demo$ mypy .
Success: no issues found in 7 source files
同样,Django Rest Framework 的包也可用:djangorest 框架存根 https://github.com/typeddjango/djangorestframework-stubs.