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
One-to-One, One-to-Many, Many-to-Many0%
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 DjangoOne-to-One, One-to-Many, Many-to-Many
Nested Serializers

One-to-One, One-to-Many, Many-to-Many

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

DRF Relational Fields: Primary Key, Slug, and Hyperlinked

In relational architectures, models reference other models. Serializing these associations in Django REST Framework requires selecting the appropriate relational field style: whether to represent related models as Primary Keys, Human-Readable Slugs, Hyperlinked URLs, or Nested JSON Objects.


1. Relational Field Styles Comparison

Relational FieldOutput FormatBest Use Case
PrimaryKeyRelatedField{"category": 5}Standard CRUD, high write efficiency
SlugRelatedField{"category": "cloud-architecture"}Clean human-readable identifiers
HyperlinkedRelatedField{"category": "https://api.com/v1/categories/5/"}Pure RESTful HATEOAS systems
StringRelatedField{"category": "Cloud Architecture"}Read-only __str__ representations
Nested Serializer{"category": {"id": 5, "name": "Cloud"}}Detailed nested object graphs

2. Implementing Relational Fields in Code

1# articles/serializers.py
2from rest_framework import serializers
3from .models import Article, Category, Tag
4 
5class ArticleRelationalSerializer(serializers.ModelSerializer):
6 # 1. PrimaryKeyRelatedField: Client passes ID integer
7 category_id = serializers.PrimaryKeyRelatedField(
8 queryset=Category.objects.all(),
9 source="category",
10 write_only=True
11 )
12 
13 # 2. SlugRelatedField: Uses human-readable unique slug
14 category_slug = serializers.SlugRelatedField(
15 slug_field="slug",
16 read_only=True,
17 source="category"
18 )
19 
20 # 3. StringRelatedField: Read-only representation using model __str__
21 author_name = serializers.StringRelatedField(source="author", read_only=True)
22 
23 # 4. ManyToMany field via SlugRelatedField
24 tags = serializers.SlugRelatedField(
25 many=True,
26 slug_field="title",
27 queryset=Tag.objects.all()
28 )
29 
30 # 5. HyperlinkedRelatedField: Output full URL to detail view
31 url = serializers.HyperlinkedIdentityField(
32 view_name="article-detail",
33 lookup_field="slug"
34 )
35 
36 class Meta:
37 model = Article
38 fields = [
39 "url",
40 "id",
41 "title",
42 "slug",
43 "author_name",
44 "category_slug",
45 "category_id",
46 "tags",
47 ]

Serialized JSON Output:

1{
2 "url": "https://api.enterprise.com/v1/articles/modern-django/",
3 "id": 101,
4 "title": "Modern Django Architecture",
5 "slug": "modern-django",
6 "author_name": "Dr. Sumit",
7 "category_slug": "backend-engineering",
8 "tags": ["python", "django", "drf"]
9}

3. The HyperlinkedModelSerializer

Instead of returning integer primary keys, HyperlinkedModelSerializer automatically uses HyperlinkedRelatedField for all relationships and includes a url field:

1class CategoryHyperlinkedSerializer(serializers.HyperlinkedModelSerializer):
2 class Meta:
3 model = Category
4 fields = ["url", "id", "name", "slug"]
5 extra_kwargs = {
6 "url": {"view_name": "category-detail", "lookup_field": "slug"}
7 }

Notice: When using HyperlinkedModelSerializer, the serializer context must include the request object (which ViewSets do automatically):

1serializer = CategoryHyperlinkedSerializer(instance, context={"request": request})

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the output of a PrimaryKeyRelatedField?
Question 2
What requirement must a model field satisfy to be used in a SlugRelatedField?
Question 3
Why is context={'request': request} required when initializing a HyperlinkedModelSerializer?
Question 4
What is the behavior of StringRelatedField?
Question 5
When writing to a relationship using SlugRelatedField(slug_field="name", queryset=Tag.objects.all()), what does DRF do?
Next Lesson

Nested Serializers

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

Related Lessons

Previous LessonNext Lesson
Pagination TechniquesNested Serializers

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