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 是做什么用的?
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
