Django中使用的“related_name”是什么? [英] What is `related_name` used for in Django?

查看:487
本文介绍了Django中使用的“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 指定从用户模型返回到您的模型的反向关系的名称。

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

如果您 指定,例如 user $ User.map_set 仍然可以工作,但 User.maps。语法显然有点清洁,不太笨重;所以例如,如果你有一个用户对象 current_user ,你可以使用 current_user.maps.all()来获取与 current_user 有关系的 Map 模型的所有实例。

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文档有更多的细节。

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

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