什么是related_name 用于? [英] What is related_name used for?

查看:76
本文介绍了什么是related_name 用于?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.all().

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 文档有更多详情.

这篇关于什么是related_name 用于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆