Django模型的类型注释 [英] Type annotations for Django models

查看:395
本文介绍了Django模型的类型注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Django项目.由于这是一个新项目,因此我希望使用python 3.6+类型注释对其进行完全注释.我正在尝试对模型进行注释,但是我很难为此找到一个好的方法.

I'm working on a Django project. Since this is a new project, I want to have it fully annotated with python 3.6+ type annotations. I'm trying to annotate models, but I struggle to find a good method for that.

让我们以IntegerField为例.我看到两种注释方式:

Let's take the IntegerField as an example. I see two choices for annotating it:

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

# number 2
int_field: models.IntegerField = models.IntegerField()

数字1在mypy中失败:

Number 1 fails in mypy:

Incompatible types in assignment (expression has type "IntegerField[<nothing>, <nothing>]", variable has type "int")

mypy的数字2是可以的,但是IDE的PyCharm无法解决它,并且经常抱怨使用了错误的类型.

Number 2 is OK for mypy, but IDE's as PyCharm are not able to resolve it and are often complaining about wrong types used.

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

Are there any best practices to correctly annotate the models, which will satisfy mypy and IDE's?

推荐答案

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

Django models (and other components) are hard to annotate because there is a lot of magic behind them, good news is that a group of cool developers have already done the hard work for us.

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

django-stubs provides a set of stubs and mypy plugins which provide static types and type inference for 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)

要对其进行修复,只需安装该软件包即可

To fix it, it's enough to install the package

pip install django-stubs

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

and create a setup.cfg file with the following:

[mypy]
plugins =
    mypy_django_plugin.main

strict_optional = True

[mypy.plugins.django-stubs]
django_settings_module = demo.settings

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

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

Once this is done, mypy will be able to infer and check annotations for Django models (and other components).

demo$ mypy .
Success: no issues found in 5 source files


这是一个小视图用法的示例:


Here is an example of the usage in a small view:

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再一次对提供的注释感到满意:

Once again, mypy is happy with the provided annotations:

demo$ mypy .
Success: no issues found in 7 source files


同一点,还提供了Django Rest Framework的软件包: djangorestframework-stubs

这篇关于Django模型的类型注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆