DRF Nested Serializer
Adds support for writable nested serializers to the Django REST framework.
Find out more with the full documentation.
Features
- All relationship types
- Including through model
- Drop-in replacement
- Create and update support
- Flexible field in- and exclusion
Example
from rest_framework.serializers import ModelSerializer
from drf_nested_serializer.serializer import NestedSerializer
from .models import MyChildModel, MyParentModel
class MyChildSerializer(ModelSerializer):
class Meta:
model = MyChildModel
fields = ("id", "")
class MyParentSerializer(NestedSerializer):
nested = MyChildSerializer()
class Meta:
model = MyParentModel
fields = ("id", "nested")
data = {
"child": {
"name": "John Doe"
}
}
serializer = MyParentSerializer(data=data)
if serializer.is_valid():
instance = serializer.save()
print(MyParentSerializer(instance=instance).data)
{
"id": 1,
"child": {
"id": 1,
"name": "John Doe"
}
}