[英]Django: typehinting backward / related_name / ForeignKey relationships
Let's say we have the following models:假设我们有以下模型:
class Site(models.Model):
# This is djangos build-in Site Model
pass
class Organization(models.Model):
site = models.OneToOneField(Site)
And if I use this somewhere in some other class:如果我在其他 class 的某个地方使用它:
organization = self.site.organization
Then mypy complains:然后mypy抱怨:
Site has no attribute "organization"
How can I make mypy happy here?我怎样才能让 mypy 在这里开心?
I just know a litle of english, and i don't know this is true.我只懂一点英语,我不知道这是不是真的。 But you can add
但是你可以添加
site = models.OneToOneField(Site, on_delete=models.CASCADE)
站点 = models.OneToOneField(站点,on_delete=models.CASCADE)
You need to set the related_name
attribute:您需要设置
related_name
属性:
class Organization(models.Model):
site = models.OneToOneField(Site, related_name="organization")
Django adds backwards relations at runtime which aren't caught by mypy
which only does static analysis. Django 在运行时添加了反向关系,mypy 无法捕获这些关系,
mypy
仅进行 static 分析。
To make mypy
happy (and to make it work with your editor's autocomplete) you need to add an explicit type hint to Site
:为了让
mypy
满意(并使其与编辑器的自动完成功能一起使用),您需要向Site
添加显式类型提示:
class Site(models.Model):
organization: "Organization"
class Organization(models.Model):
site = models.OneToOneField(Site)
Using quotes around the type is needed since we are doing a forward reference to Organization
before it has been defined.需要在类型周围使用引号,因为我们在定义
Organization
之前对其进行了前向引用。
For foreign keys and many-to-many relationships, you can do the same thing, but using a QuerySet
type hint instead:对于外键和多对多关系,您可以做同样的事情,但使用
QuerySet
类型提示代替:
class Organization(models.Model):
site = models.OneToOneField(Site)
employees: models.QuerySet["Employee"]
class Employee(models.Model):
organization = models.ForeignKey(
Organization,
on_delete=models.CASCADE,
related_name="employees",
)
EDIT: There is a django-stubs package which is meant to integrate with mypy
, however I haven't used it personally.编辑:有一个django-stubs package 旨在与
mypy
集成,但是我没有亲自使用它。 It may provide a solution for this without having to explicitly add type hints to models.它可以为此提供解决方案,而无需向模型显式添加类型提示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.