StringRelatedField
The StringRelatedField represents the target of the relationship using its __str__ method. This field is read-only and set the ‘many’ argument to true If more than one instance to serialize. Let’s make use of StringRelatedField for tasks filed in EmployeeSerializer class. The relationship generator process as follows:
tasks = serializers.StringRelatedField(many=True)
The EmployeeSerializer class as follows:
Python3
class EmployeeSerializer(serializers.ModelSerializer): # StringRelatedField tasks = serializers.StringRelatedField(many = True ) class Meta: model = Employee fields = ( 'pk' , 'emp_id' , 'name' , 'gender' , 'designation' , 'tasks' ) |
Let’s retrieve the employee details to understand how the StringRelatedField displays the relationship field values. The HTTPie command to retrieve the employee values is:
http :8000/employees/
Output
HTTP/1.1 200 OK Content-Length: 279 Content-Type: application/json Date: Fri, 22 Jan 2021 04:04:08 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": [ "Binary Search", "Interchange first and last elements in a list" ] }, { "designation": "Test Engineer", "emp_id": 129, "gender": "F", "name": "Jeena R", "pk": 9, "tasks": [] } ]
Sharing the command prompt screenshot for your reference
Here you can notice that the tasks field displays the string value from the function def __str__(self): in the EmployeeTask model.
def __str__(self): return self.task_name
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