related_name 是做什么用的?

2022-01-20 00:00:00 python django many-to-many foreign-keys

问题描述

related_name 参数对 ManyToManyFieldForeignKey 字段有什么用处?比如给定下面的代码,related_name='maps'的作用是什么?

What is the related_name argument useful for on ManyToManyField and ForeignKey fields? For example, given the following code, what is the effect of related_name='maps'?

class Map(db.Model):
    members = models.ManyToManyField(User, related_name='maps',
                                     verbose_name=_('members'))


解决方案

related_name 属性指定从 User 模型返回到您的模型的反向关系的名称.

The related_name attribute specifies the name of the reverse relation from the User model back to your model.

如果你没有指定 related_name,Django 会自动使用你的模型名称和后缀 _set 创建一个,例如 User.map_set.全部().

If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set, for instance User.map_set.all().

如果您做指定,例如related_name=mapsUser 模型上,User.map_set 仍然有效,但 User.maps. 语法显然更干净,不那么笨重;例如,如果您有一个用户对象 current_user,您可以使用 current_user.maps.all() 来获取 Map 的所有实例与 current_user 相关的模型.

If you do specify, e.g. related_name=maps on the User model, User.map_set will still work, but the User.maps. syntax is obviously a bit cleaner and less clunky; so for example, if you had a user object current_user, you could use current_user.maps.all() to get all instances of your Map model that have a relation to current_user.

Django 文档有更多详情.

相关文章