related_name的作用是什么? [英] What does related_name do?
问题描述
在有关 related_name
的Django文档中,其内容如下:
In the Django documentation about related_name
it says the following:
用于从相关对象到此对象的关系的名称.也是
related_query_name
的默认值(用于目标模型中反向过滤器名称的名称).有关完整的解释和示例,请参见相关的对象文档.注意,在抽象模型上定义关系时必须设置此值.并且当您这样做时,可以使用一些特殊的语法.
The name to use for the relation from the related object back to this one. It’s also the default value for
related_query_name
(the name to use for the reverse filter name from the target model). See the related objects documentation for a full explanation and example. Note that you must set this value when defining relations on abstract models; and when you do so some special syntax is available.
如果您不希望Django不要创建向后关系,请将related_name设置为'+'或以'+'结尾.
If you’d prefer Django not to create a backwards relation, set related_name to '+' or end it with '+'.
我不清楚.如果有人能再解释一下,那对我会有很大帮助.
I didn't understand it clearly. If somebody would please explain it a bit more, it would help me a lot.
推荐答案
创建外键时,您要将两个模型链接在一起.带有 ForeignKey()
字段的模型使用字段名称来查找其他模型.还会在链接模型中隐式添加一个成员,以回溯此成员.
When you create a foreign key, you are linking two models together. The model with the ForeignKey()
field uses the field name to look up the other model. It also implicitly adds a member to the linked model referring back to this one.
class Post(models.Model):
# ... fields ...
class Comment(models.Model):
# ... fields ...
post = models.ForeignKey(Post, related_name=???)
这里有三种可能的情况:
There are three possible scenarios here:
如果您未指定名称,django将默认为您创建一个名称.
If you don't specify a name, django will create one by default for you.
some_post = Post.objects.get(id=12345)
comments = some_post.comment_set.all()
默认名称是关系的名称+ _set
.
The default name is the relation's name + _set
.
通常,您需要指定一些使其更自然的东西.例如, related_name ="comments"
.
Usually you want to specify something to make it more natural. For example, related_name="comments"
.
some_post = Post.objects.get(id=12345)
comments = some_post.comments.all()
3.防止创建反向引用
有时您不想添加对外部模型的引用,因此请使用 related_name ="+"
来创建它.
some_post = Post.objects.get(id=12345)
comments = some_post.comment_set.all() # <-- error, no way to access directly
related_query_name
基本上是相同的想法,但是在查询集上使用 filter()
时:
related_query_name
is basically the same idea, but when using filter()
on a queryset:
posts_by_user = Post.objects.filter(comments__user__id=123)
但是,老实说,因为默认使用 related_name
值,所以我从未使用过它.
But to be honest I've never used this since the related_name
value is used by default.
这篇关于related_name的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!