[Fixed]-How will I serialize complex Django Models to json?

1๐Ÿ‘

โœ…

You have to use nested Relationships to do this job :

Here is an example :

class SubjectSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=200)

    class Meta:
        fields = [
            'name',
        ]

class StudentSerializer(serializers.Serializer):
    first_name = serializers.CharField(max_length=200)
    middle_name = serializers.CharField(max_length=200)
    last_name = serializers.CharField(max_length=200)
    # nested relationship
    subjects = SubjectSerializer(many=True)

    class Meta:
        fields = [
            'first_name',
            'last_name',
            'middle_name',
            'subjects'
        ]

Read Django Rest Framework โ€“ Nested relationships for more information

0๐Ÿ‘

You are looking for nested serializers.
The documentation should cover everything you need to know about this.

Please also take some time to run the 6 steps of the tutorial. It will give you hints about how to use DRF.

๐Ÿ‘คLinovia

Leave a comment