drf ModelSerializer serialize custom field from json code example
Example 1: how to add methods to manuplate the model in serializers
from rest_framework import serializers, status
from models import *
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email')
class StudentSerializer(serializers.ModelSerializer):
"""
A student serializer to return the student details
"""
user = UserSerializer(required=True)
class Meta:
model = UnivStudent
fields = ('user', 'subject_major',)
def create(self, validated_data):
"""
Overriding the default create method of the Model serializer.
:param validated_data: data containing all the details of student
:return: returns a successfully created student record
"""
user_data = validated_data.pop('user')
user = UserSerializer.create(UserSerializer(), validated_data=user_data)
student, created = UnivStudent.objects.update_or_create(user=user,
subject_major=validated_data.pop('subject_major'))
return student
Example 2: how to add methods to manuplate the model in serializers
from django.db import models
from django.contrib.auth.models import User
class UnivStudent(models.Model):
"""
A class based model for storing the records of a university student
Note: A OneToOne relation is established for each student with User model.
"""
user = models.OneToOneField(User)
subject_major = models.CharField(name="subject_major", max_length=60)