Recursive Serialization for Django REST framework

0.1.2 · abandoned · verified Thu Apr 16

djangorestframework-recursive is a Python library that provides a `RecursiveField` for Django REST Framework serializers, enabling the serialization of tree, linked list, or directed acyclic graph structures. Maintained by @heywbj, the last release (0.1.2) was on July 4, 2017. Due to a lack of recent maintenance, users requiring compatibility with modern Django and Django REST Framework versions are advised to consider the actively maintained fork, `drf-recursive`.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a recursive serializer for a tree-like structure using `RecursiveField`. It assumes a conceptual `Category` model with a self-referential `parent` foreign key, allowing for nested children. The `RecursiveField` automatically handles the self-referencing serialization.

from rest_framework import serializers
from rest_framework_recursive.fields import RecursiveField

# Example Model (assuming you have a Django model like this)
# class Category(models.Model):
#     name = models.CharField(max_length=100)
#     parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')

class CategorySerializer(serializers.Serializer):
    name = serializers.CharField(max_length=100)
    children = serializers.ListField(child=RecursiveField(), required=False)

# Example usage with a dummy data structure
# In a real application, you would pass Django model instances
data = {
    'name': 'Root',
    'children': [
        {
            'name': 'Child 1',
            'children': [
                {'name': 'Grandchild 1.1'},
                {'name': 'Grandchild 1.2'}
            ]
        },
        {'name': 'Child 2'}
    ]
}

serializer = CategorySerializer(data=data)
if serializer.is_valid():
    print(serializer.data)
else:
    print(serializer.errors)

view raw JSON →