Django中“ related_name”和“ related_query_name”属性之间的区别? [英] Difference between 'related_name' and 'related_query_name' attributes in Django?
问题描述
您能解释Django中Field对象的 related_name
和 related_query_name
属性之间的区别吗?当我使用它们时,如何使用它们?谢谢!
Can you explain the difference between related_name
and related_query_name
attributes for the Field object in Django ? When I use them, How to use them? Thanks!
推荐答案
related_name
将是相关对象的属性,允许您向后转到带有外键的模型。例如,如果 ModelA
的字段类似于: model_b = ForeignKeyField(ModelB,related_name ='model_as')
,则此字段将使您可以通过转到 model_b_instance访问与您的
。请注意,对于外键,这通常用复数形式编写,因为外键是一对多关系,并且该等式的多面是声明了外键字段的模型。 ModelB
实例相关的 ModelA
实例.model_as.all()
related_name
will be the attribute of the related object that allows you to go 'backwards' to the model with the foreign key on it. For example, if ModelA
has a field like: model_b = ForeignKeyField(ModelB, related_name='model_as')
, this would enable you to access the ModelA
instances that are related to your ModelB
instance by going model_b_instance.model_as.all()
. Note that this is generally written with a plural for a Foreign Key, because a foreign key is a one to many relationship, and the many side of that equation is the model with the Foreign Key field declared on it.
文档中链接的进一步说明很有帮助。 https://docs.djangoproject.com/en/ dev / topics / db / queries /#backwards-related-objects
The further explanation linked to in the docs is helpful. https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects
related_query_name
在Django查询集中。它使您可以过滤与外键相关字段的反向关系。继续我们的示例-在 Model A
上有一个字段,例如:
model_b = ForeignKeyField(ModelB,related_query_name ='model_a')
将使您能够使用 model_a
作为查询集中的查找参数,例如: ModelB.objects.filter(model_a = whatever)
。 related_query_name
使用单数形式更为常见。正如文档所述,不必同时指定 related_name
和 related_query_name
(或两者中的一个)。 Django有合理的默认值。
related_query_name
is for use in Django querysets. It allows you to filter on the reverse relationship of a foreign key related field. To continue our example - having a field on Model A
like:
model_b = ForeignKeyField(ModelB, related_query_name='model_a')
would enable you to use model_a
as a lookup parameter in a queryset, like: ModelB.objects.filter(model_a=whatever)
. It is more common to use a singular form for the related_query_name
. As the docs say, it isn't necessary to specify both (or either of) related_name
and related_query_name
. Django has sensible defaults.
这篇关于Django中“ related_name”和“ related_query_name”属性之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!