MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Nested Serializers0%
Study Materials
REST API Development with DjangoProgress 0%
1.1REST Principles1.2HTTP Methods Overview1.3Status Codes
6.1One-to-One, One-to-Many, Many-to-Many6.2Nested Serializers6.3Handling Related Objects
HomeTutorialsREST API Development with DjangoNested Serializers
Handling Related Objects

Nested Serializers

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

In relational domain models, parent and child records are tightly coupled. For example, an Invoice contains multiple InvoiceItems, or an Order contains multiple OrderLineItems. While reading nested data is straightforward in DRF, writable nested serializers (creating or updating parent and child objects in a single API request) require implementing custom create() and update() methods.


1. Read-Only Nested Serialization

Embedding related child representations in read responses is accomplished by nesting child serializers:

1# billing/serializers.py
2from rest_framework import serializers
3from .models import Invoice, InvoiceItem
4 
5class InvoiceItemSerializer(serializers.ModelSerializer):
6 class Meta:
7 model = InvoiceItem
8 fields = ["id", "description", "quantity", "unit_price", "total_price"]
9 
10class InvoiceDetailSerializer(serializers.ModelSerializer):
11 # Read-only nested array of items
12 items = InvoiceItemSerializer(many=True, read_only=True)
13 
14 class Meta:
15 model = Invoice
16 fields = ["id", "invoice_number", "customer_name", "created_at", "items"]

2. The Writable Nested Challenge

By default, calling serializer.save() on a nested serializer with writable fields raises an error:

"The .create() method does not support writable nested fields by default. Write an explicit .create() on this serializer."

Because Django models cannot guess how you wish to handle relational children (whether to update, delete, or create new rows), you must explicitly implement create() and update().


3. Implementing Writable create()

1# billing/serializers.py
2class InvoiceItemWriteSerializer(serializers.ModelSerializer):
3 class Meta:
4 model = InvoiceItem
5 fields = ["description", "quantity", "unit_price"]
6 
7class InvoiceCreateSerializer(serializers.ModelSerializer):
8 # Writable nested items array
9 items = InvoiceItemWriteSerializer(many=True)
10 
11 class Meta:
12 model = Invoice
13 fields = ["invoice_number", "customer_name", "items"]
14 
15 def create(self, validated_data):
16 # 1. Pop nested child data out of validated_data
17 items_data = validated_data.pop("items", [])
18 
19 # 2. Create the parent Invoice instance
20 invoice = Invoice.objects.create(**validated_data)
21 
22 # 3. Create each child InvoiceItem bound to parent invoice
23 for item_data in items_data:
24 InvoiceItem.objects.create(invoice=invoice, **item_data)
25 
26 return invoice

4. Implementing Writable update()

Updating nested records requires handling three possibilities:

  1. 1
    Existing items that were modified.
  2. 2
    New items added to the array.
  3. 3
    Items omitted from the array that should be deleted.
1 def update(self, instance, validated_data):
2 items_data = validated_data.pop("items", None)
3 
4 # Update parent fields
5 instance.invoice_number = validated_data.get("invoice_number", instance.invoice_number)
6 instance.customer_name = validated_data.get("customer_name", instance.customer_name)
7 instance.save()
8 
9 if items_data is not None:
10 # Simple strategy: Replace existing items with incoming set
11 instance.items.all().delete()
12 for item_data in items_data:
13 InvoiceItem.objects.create(invoice=instance, **item_data)
14 
15 return instance

5. Client JSON Request Body

The client can now create the complete parent and children in a single HTTP request:

1POST /api/v1/invoices/ HTTP/1.1
2Content-Type: application/json
3 
4{
5 "invoice_number": "INV-2026-0042",
6 "customer_name": "Acme Global Corp",
7 "items": [
8 { "description": "Cloud Hosting Enterprise", "quantity": 1, "unit_price": 1200.00 },
9 { "description": "DevOps Maintenance", "quantity": 10, "unit_price": 150.00 }
10 ]
11}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Why does DRF raise an error if you attempt to save a ModelSerializer with writable nested fields without defining .create()?
Question 2
What Python method removes the nested list from validated_data so the parent model can be instantiated cleanly?
Question 3
What is a primary performance consideration when reading deeply nested serializers?
Question 4
How do you mark a nested serializer as strictly read-only?
Question 5
What is the benefit of writable nested serializers for API clients?
Next Lesson

Handling Related Objects

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
One-to-One, One-to-Many, Many-to-ManyHandling Related Objects

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master REST API Development with Django with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext