Các mô hình Django (và các thành phần khác) rất khó để chú thích vì có rất nhiều phép thuật đằng sau chúng, tin tốt là một nhóm các nhà phát triển tuyệt vời đã thực hiện công việc khó khăn cho chúng tôi.
django-stub cung cấp một tập hợp các sơ khai và plugin mypy cung cấp các kiểu tĩnh và suy luận kiểu cho Django.
Ví dụ: có mô hình sau:
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 sẽ phàn nàn rằng:
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)
Để khắc phục, nó đủ để cài đặt gói
pip install django-stubs
và tạo một setup.cfg
tệp với các mục sau:
[mypy]
plugins =
mypy_django_plugin.main
strict_optional = True
[mypy.plugins.django-stubs]
django_settings_module = demo.settings
(Đừng quên cập nhật django_settings_module
theo mô-đun cài đặt của bạn)
Một khi điều này được thực hiện, mypy sẽ có thể suy luận và kiểm tra các chú thích cho các mô hình Django (và các thành phần khác).
demo$ mypy .
Success: no issues found in 5 source files
Dưới đây là một ví dụ về việc sử dụng trong một chế độ xem nhỏ:
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()})
Một lần nữa, mypy hài lòng với các chú thích được cung cấp:
demo$ mypy .
Success: no issues found in 7 source files
Cùng một lưu ý, một gói cho Django Rest Framework cũng có sẵn: djangorestframework-stub .