Skip to content

Conversation

HosseinSayyedMousavi
Copy link

Add SerializedRelatedField for write-by-slug, read-as-nested representation

Description

Currently, SlugRelatedField only returns the slug value (e.g. a PK or custom field).
Nested serializers, on the other hand, expand the related object but require verbose input payloads.

In many APIs, developers want a hybrid behavior:

  • Write: accept a simple slug (e.g. "address": 5)
  • Read: return the full nested representation via another serializer

This PR introduces SerializedRelatedField, which:

  • Behaves like SlugRelatedField on writes
  • Expands to a nested serializer on reads (if serializer_class is provided)

Example

from rest_framework import serializers
from myapp.models import Address
from myapp.serializers import AddressSerializer
from rest_framework.fields import SerializedRelatedField

class OrderSerializer(serializers.ModelSerializer):
    address = SerializedRelatedField(
        serializer_class=AddressSerializer,
        queryset=Address.objects.all(),
        lookup_field="pk"
    )

Request

{
  "address": 5
}

Response

{
  "address": {
    "id": 5,
    "province": "Tehran",
    "city": "Tehran",
    "street": "Valiasr",
    "additional_info": "Test info"
  }
}

References


Testing

Tested locally using django.test.TestCase:

python runtests.py tests/test_relations.py::SerializedRelatedFieldTests

Covers both:

  • Writing a related object by slug/PK
  • Reading a related object with nested serialization

💡 Note: This feature provides a more convenient and expressive way to handle related fields in DRF, reducing boilerplate code and improving API readability.

…tation

- Introduce SerializedRelatedField in rest_framework/relations.py
- Supports writing by slug/PK and reading as nested serializer
- Add corresponding tests in tests/test_relations.py
@HosseinSayyedMousavi HosseinSayyedMousavi force-pushed the feature/serialized-slug-related-field branch from 4c7ab6e to 67a800b Compare September 19, 2025 21:22
@auvipy auvipy self-requested a review September 20, 2025 11:53
@p-r-a-v-i-n
Copy link

DRF is considered to be featured complete as per the contributing guidlines.
https://www.django-rest-framework.org/community/contributing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants