Djangoモデル(およびその他のコンポーネント)は、背後に多くの魔法があるため、注釈を付けるのが困難です。良いニュースは、クールな開発者のグループがすでに私たちのために大変な作業を行っていることです。
django- stubsは、Djangoに静的型と型推論を提供する一連のスタブとmypyプラグインを提供します。
たとえば、次のモデルがあるとします。
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]
plugins =
mypy_django_plugin.main
strict_optional = True
[mypy.plugins.django-stubs]
django_settings_module = demo.settings
(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のパッケージdjangorestframework-stubsも利用できます。