HyperlinkedRelatedField

HyperlinkedRelatedField is used to represent the target of the relationship using a Hyperlink. By default, this field is a read-write, but we can make it read-only by setting the read-only flag True. The arguments of HyperlinkedRelatedField are as follows:

  • view_name – The view name is used as the target of the relationship. For standard router classes, this will be a string with the format <modelname>-detail.
  • queryset – It facilitates model instance lookups when validating the field input. Relationships must either set a queryset explicitly or set read_only=True.
  • many – To serialize more than one relation, you should set this argument to True.
  • allow_null – If set to True, the field will accept None values or the empty string for nullable relationships. Defaults to False.
  • lookup_field – The field on the target is used for the lookup. It corresponds to a URL keyword argument on the referenced view. Default is ‘pk’.
  • lookup_url_kwarg – The name of the keyword argument defined in the URL conf that corresponds to the lookup field. By default, it uses the same value as lookup_field.
  • format – If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the format argument.

In our reverse relationship (Employee to EmployeeTask) we have seen that by default the serializer (EmployeeSerializer) uses the primary key to represent the target of a relationship (to include a reverse relationship, you must explicitly add it to the field list). We have also explored other representations such as StringRelatedField and SlugRelatedField. Here, we will make use of HyperlinkedRelatedField.

In the EmployeeSerializer class, you can use represent the tasks field as shown below:

tasks = serializers.HyperlinkedRelatedField(many=True,
                                            read_only=True,
                                            view_name='employeetask-detail')

You can replace the existing EmployeeSerializer class with the below one:

Python3




class EmployeeSerializer(serializers.HyperlinkedModelSerializer):
    url = serializers.HyperlinkedIdentityField(
        view_name='employee-detail',
        lookup_field='pk'
    )
    tasks = serializers.HyperlinkedRelatedField(many=True,
                                                read_only=True,
                                                view_name='employeetask-detail')
          
      
    class Meta:
        model = Employee
        fields = (
            'url',
            'pk',
            'emp_id',
            'name',
            'gender',
            'designation',
            'tasks')


The HTTPie command is:

http GET :8000/employees/8/

Output

HTTP/1.1 200 OK
Content-Length: 283
Content-Type: application/json
Date: Fri, 22 Jan 2021 16:18:59 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.7.5
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

{
    "designation": "Software Engineer",
    "emp_id": 128,
    "gender": "M",
    "name": "Mathew A",
    "pk": 8,
    "tasks": [
        "http://localhost:8000/task/2/",
        "http://localhost:8000/task/1/",
        "http://localhost:8000/task/6/",
        "http://localhost:8000/task/7/"
    ],
    "url": "http://localhost:8000/employees/8/"
}

Sharing the command prompt screenshot for your reference

If we analyze the output, we can notice that the tasks field displays a set, or hyperlinks.

"tasks": [
        "http://localhost:8000/task/2/",
        "http://localhost:8000/task/1/",
        "http://localhost:8000/task/6/",
        "http://localhost:8000/task/7/"
    ]

Next, let’s understand how the nested relationship can be expressed by using serializers as fields. 

Serializer Relations – Django REST Framework

Serialization is one of the most important concepts in RESTful Webservices.  It facilitates the conversion of complex data (such as model instances) to native Python data types that can be rendered using JSON, XML, or other content types. In Django REST Framework, we have different types of serializers to serialize object instances, and the serializers have different serializer relations to represent model relationships. In this section, we will discuss the different serializer relations provided by Django REST Framework Serializers. 

Table of Contents

  • Getting Started
  • Creating Django Models and Views
  • PrimaryKeyRelatedField
  • StringRelatedField
  • SlugRelatedField
  • HyperlinkedIndetityField
  • HyperlinkedRelatedField
  • Nested Relationship

Similar Reads

Getting Started

Before working on Django REST Framework serializers, you should make sure that you already installed Django and Django REST Framework in your virtual environment. You can check the below tutorials:...

Creating Django Models and Views

Creating Django Models...

PrimaryKeyRelatedField

...

StringRelatedField

...

SlugRelatedField

...

HyperlinkedIndetityField

...

HyperlinkedRelatedField

...

Nested Relationship

PrimaryKeyRelatedField represents the target of the relation using the primary key (pk). It can be achieved by generating the relationship using the rest_framework.serializers.PrimaryKeyRelatedField() field. By default, this field is read-write, but you can make it read-only by setting the read_only attribute to True. The PrimaryKeyRelatedField has the following arguments:...

Contact Us