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 是做什么用的?
基础教程推荐
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
