Search code examples
django-rest-frameworkdjango-serializer

How to form JSON object so that it could be deserialized by nested model serializer


I have two models CompanyDetails and User for which I have created two ModelSerializer as CompanyDetailsSerializer and RegisterUserSerializer.

CompanyDetailsSerializer

class CompanyDetailsSerializer(serializers.ModelSerializer):

    class Meta:
        model = CompanyDetails
        fields = ['id', 'company_name', 'is_active']
        extra_kwargs = {
            'company_name' : {
                'required' : True,
                'allow_null' : False,
                'allow_blank' : False
            

} }

RegisterUserSerializer

class RegisterUserSerializer(serializers.ModelSerializer):
    '''
    This serializer is for Register User view.
    '''
    company = CompanyDetailsSerializer()

    class Meta:
        model = User
        fields = ['id', 'first_name', 'last_name', 'email', 'mobile_number', 'company', 'password']
        extra_kwargs = {
            'first_name' : {
                'required' : True,
                'allow_null' : False,
                'allow_blank' : False
            },
            'last_name' : {
                'required' : True,
                'allow_null' : False,
                'allow_blank' : False
            },
            'email' : {
                'required' : True,
                'allow_null' : False,
                'allow_blank' : False
            },
            'mobile_number' : {
                'required' : True,
            },
            'password' : {
                'required' : True,
                'allow_blank' : False,
                'allow_null' : False,
                'write_only': True
            }
        }

The request.data has following JSON which is further serialized by RegisterUserSerializer -

{
    "first_name": "Jeet",
    "last_name": "Patel",
    "mobile_number": 9765136777,
    "email": "jpatel99967@gmail.com",
    "password": "123456",
    "comapany": {
        "company_name": "Yantra Inc"
    }
}

But the RegisterUserSerializer generates the error stated below.

{
    "company": [
        "This field is required."
    ]
}

How should I send the JSON data to the serializer?


Solution

  • For starters, you have a typo in your data: comapny instead of company.

    Assuming User has a Foreign Key to Company, then the filed company in you User JSON data should be a valid Company Primary Key.