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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Django __str__ returned non-string (type NoneType)
- Evil ctypes hack in python
The obvious answer is that
HyperLinkedIdentityField
is meant to point to the current object only, whereasHyperLinkedRelatedField
is meant to point to something that the current object references. I suspect under the hood the two are different only in that the identity field has less work to do in order to find the related model's URL routes (because the related model is the current model), while the related field has to actually figure out the right URLs for some other model.In other words,
HyperLinkedIdentityField
is lighter-weight (more efficient), but won't work for models other than the current model.You would use a
HyperlinkedIdentityField
to link to the object currently being serialized and aHyperlinkedRelatedField
to link to objects related to the one being serialized.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 aHyperlinkedRelatedField
is used is for theurl
field which you can include on your serializer to point to the current object.In Django REST framework 3.0.0, there are only two differences between a
HyperlinkedRelatedField
andHyperlinkedIdentityField
.source
is automatically set to*
(the current object)read_only=True
, so it can't be changedWhich means that setting a
HyperlinkedRelatedField
with those properties is exactly the same as having aHyperlinkedIdentityField
.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 ofHyperlinkedRelatedField
.