Django 向后关系会增加开销吗?

Do Django backward relations add overhead?

在 Django 中,您创建模型并可以选择在字段上指定外键

class Man:
      ...

class Dog:
      ...
      owner = models.ForeignKey(Man, on_delete=models.SET_NULL)

然后您可以为每个 Dog 查询其各自的所有者或获取所有狗 Man

owner = some_dog.owner

all_dogs = some_man.dog_set.all()

如果你不想创建the docs指定的后向关系,你可以

class Man:
      ...

class Dog:
      ...
      owner = models.ForeignKey(Man, on_delete=models.SET_NULL, related_name='+')

现在您无法再访问 all_dogs = some_man.dog_set.all()

但是,这种额外的 "building" 向后关系是否会增加开销?
如果我从来没有用过 all_dogs = some_man.dog_set.all() 是否重要
我在 Dog 中指定了 related_name='+'?它可能会减慢速度吗?

这个功能是纯粹在应用程序端 Django 中实现的,还是 related_name='+' 也会更改数据库架构本身?

However, does this additional "building" of a backward relation add overhead?

没有

If I just never ever used all_dogs = some_man.dog_set.all() would it matter whether or not I had specified related_name='+' in Dog? Would it slow things down potentially?

没有,也没有。

And is this functionality purely implemented in application side Django, or would related_name='+' also change the database schema itself?

它是用 Python descriptors. In the case of ForeignKey, that's a ReverseManyToOneDescriptor 实现的。 数据库架构没有变化,相关名称的存在与否不会生成迁移。

如果您没有禁用关系,您实际上应该看到描述符对象作为模型的属性类。像这样:

>>> Dog.owner
<django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor at 0x105db25d0>
>>> Man.dog_set
<django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor at 0x105db27d0>

这些是使 Django 的 ORM 魔术发挥作用的对象。