对于Django Rest Framework,HyperLinkedRelatedField和HyperLinkedIdentityField用例有何区别? [英] For Django Rest Framework, what is the difference in use case for HyperLinkedRelatedField and HyperLinkedIdentityField?
问题描述
我当然检查过这些文档,但想知道是否有人能更简洁地解释这些领域之间用例和应用程序的区别。为什么一个使用一个字段而不是另一个?
I've of course reviewed the docs, but was wondering if anyone could more succinctly explain the difference in use case and application between these fields. Why would one use one field over the other? Would there be a difference between these fields for a OneToOne relationship?
推荐答案
您将使用 HyperlinkedIdentityField
链接到当前正在序列化的对象,而 HyperlinkedRelatedField
链接到与正在序列化的对象有关的对象。
You would use a HyperlinkedIdentityField
to link to the object currently being serialized and a HyperlinkedRelatedField
to link to objects related to the one being serialized.
因此,对于一对一关系,外键关系,多对多关系以及基本上任何其他涉及关系的关系(在Django模型中),您想使用 HyperlinkedRelatedField
。唯一使用 HyperlinkedRelatedField
的时间是 url
字段,您可以将其包含在序列化程序中以指向当前对象。
So for a one-to-one relationship, foreign key relationship, many-to-many relationship and basically anything else involving relationships (in Django models), you want to use a HyperlinkedRelatedField
. The only time where a HyperlinkedRelatedField
is used is for the url
field which you can include on your serializer to point to the current object.
在Django REST Framework 3.0.0中,有只有两个区别在 HyperlinkedRelatedField
和 HyperlinkedIdentityField
。
In Django REST framework 3.0.0, there are only two differences between a HyperlinkedRelatedField
and HyperlinkedIdentityField
.
-
源
自动设置为*
(当前对象) - 它设置为
read_only = True
,因此无法更改
- The
source
is automatically set to*
(the current object) - It is set to
read_only=True
, so it can't be changed
这意味着设置<$ c $具有这些属性的c> HyperlinkedRelatedField 与具有 HyperlinkedIdentityField
的完全相同。
Which means that setting a HyperlinkedRelatedField
with those properties is exactly the same as having a HyperlinkedIdentityField
.
在较早版本的Django REST框架(befor e 3.0.0), HyperlinkedIdentityField
曾经是专用字段,用于解析当前对象的url。它接受了稍稍的一组不同的参数,并且不是 HyperlinkedRelatedField
的子类。
In older versions of Django REST framework (before 3.0.0), the HyperlinkedIdentityField
used to be a dedicated field for resolving the url for the current object. It accepted a slightly different set of parameters and was not a subclass of HyperlinkedRelatedField
.
这篇关于对于Django Rest Framework,HyperLinkedRelatedField和HyperLinkedIdentityField用例有何区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!