I have one model serializer class with one extra field in it and i want to serialize that. Below is my serilizer..

from rest_framework import serializers
from .models import WUser


class UserTypeSerializer(serializers.Serializer):
    user_type = serializers.IntegerField(min_value=0, max_value=8, default=0)


class BaseUserSerializer(serializers.ModelSerializer):
    user_type = UserTypeSerializer()

    class Meta:
        model = WUser
        fields = ('user_type', 'username', 'email', 'first_name', 'last_name', 'password', 'mobile_no')

i am calling this serailizer with below method..

serialized_data = BaseUserSerializer(user, data={"user_type": 0, "password": password})

But this is not working..

I want serialized output in nested JSON form that is the reason i created another serializer.

Required Output

        "user_type": 0,
        "user": {
            "username": "ABCED",
            "first_name": "Deendayal",
            "last_name": "Garg",
            "email": "deen@abc.com",
            "mobile_no": "9833213601",
            "password": "hard"
        }

score:0

Your doing one unnecessary (and erroneous) indirection and your nesting your seializers backwards. Try this instead:

from rest_framework import serializers
from .models import WUser

class BaseUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = WUser
        fields = ('user_type', 'username', 'email', 'first_name', 'last_name', 'password', 'mobile_no')

class UserTypeSerializer(serializers.Serializer):
    user_type = serializers.IntegerField(min_value=0, max_value=8, default=0)
    user = BaseUserSerializer()

And create the UserTypeSerializer as the "root" (i e in view).


Related Query