[Fixed]-For Django Rest Framework, what is the difference in use case for HyperLinkedRelatedField and HyperLinkedIdentityField?

13👍

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.

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 HyperlinkedIdentityField is used is for the url 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 and HyperlinkedIdentityField, in the 2nd:

  • The source is automatically set to * (the current object)
  • It is set to read_only=True, so it can’t be changed

Which means that setting a HyperlinkedRelatedField with those properties is exactly the same as having a HyperlinkedIdentityField.


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.

5👍

The obvious answer is that HyperLinkedIdentityField is meant to point to the current object only, whereas HyperLinkedRelatedField 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.

Leave a comment