What is related_name used for?(related_name 是做什么用的?)
问题描述
related_name
参数对 ManyToManyField
和 ForeignKey
字段有什么用处?比如给定下面的代码,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=maps
在 User
模型上,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 文档有更多详情.
这篇关于related_name 是做什么用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:related_name 是做什么用的?


基础教程推荐
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01