nonstopio
Published in

nonstopio

extra_fields

💡extra_fields in Django

extra_fields are used to add extra additional fields in the serializer. Mostly it is used in custom serializer.

✨ Let’s try to understand it 👇

eg. Suppose there are Student, College, and Subjects models.

class Student(models.Model):
id = models.AutoField(primary_key=True)
student_name = models.CharField(max_length=120)
age = models.IntegerField()


class College(models.Model):
id = models.AutoField(primary_key=True)
college_name = models.CharField(max_length=120)
student = models.ForeignKey(Student,
on_delete=models.CASCADE, null=True)

class Subjects(models.Model):
id = models.AutoField(primary_key=True)
subject_name = models.CharField(max_length=120)
student = models.ForeignKey(Student, on_delete=models.CASCADE, null=True)

If we want to access student and their college and subject information then we can access it by writing a custom serializer. If we want to avoid a custom serializer then use related_name.
Now we see custom serializer

Serializer:

class StudentSerializer(serializers.ModelSerializer):
college = serializers.SerializerMethodField()
subject = serializers.SerializerMethodField()

def get_college(self, obj):
college_queryset = College.object.filter(student=obj.id)
college_list = []
for collage in college_queryset:
college_list.append(model_to_dict(college))
return college_list

def get_subject(self, obj):
subject_queryset = Subject.object.filter(student=obj.id)
subject_list = []
for subject in subject_queryset:
subject_list.append(model_to_dict(subject))
return subject_list

class Meta:
model = Student
fields = '__all__'
extra_fields = ["college", "subject"]

📝 Note: When we write a custom serializer then must pass the custom serializer name (college, subject)in the fields. Otherwise, it gives an error

Usecase: If extra_fields is not used but we want to mention "college", "subject" custom serializer name then we need to manually write all Student fields and "college", "subject".

like:

class Meta:
model = Student
fields = ("id", "student_name", "age", "college", "subject")

So simply use extra_fields so that it becomes easy to add extra fields in the serializer instead of writing all fields ✌️

Usecase Of model_to_dict:

  1. Import it
from django.forms import model_to_dict

model_to_dict is used to convert an instance to a dictionary.

🎉 🎉 🎉 🎉 🎉 🎉 🎉 🎉 🎉 🎉 🎉 🎉 🎉 🎉 🎉 🎉 🎉 🎉 🎉 🎉

--

--

--

A Bespoke Engineering Studio

Recommended from Medium

Testing in Dart: There’s life beyond Flutter.

The Night Technology Betrayed Me: A Halloween Horror Story

Saving the day with continuous refactoring

Easy HttpClient mocking

Journey To Becoming A Game Dev

READ/DOWNLOAD=# Fundamentals of Multimedia (Texts in Computer Science) FULL BOOK PDF & FULL…

Robot Asset Packs On The Unreal Engine Marketplace | Radical Robots Pack 1, 2, & 3

Front End to Full Stack.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Shweta Pawar

Shweta Pawar

More from Medium

Create and Deploy Django App in 10 Minutes Using Git & SSH

Django Queryset API Is Enough.

APIView vs Viewsets

How split Django settings.py file