Hello, I’m running into a problem un-nesting a nested serializer. Here’s an example:
class CitySerializer(serializers.ModelSerializer):
city_name = serializers.CharField()
top_school = serializers.SerializerMethodField()
def get_top_school(self, obj):
top_school = obj.top_school.get() #returns the top school for a given city
return SchoolSerializer(top_school, read_only=True).data
class Meta:
model = City
fields = (‘city_name’, ‘top_school’)
class SchoolSerializer(serializers.ModelSerializer):
school_founded_date = serializers.DateField()
school_location = serializers.CharField()
school_name = serializers.CharField()
class Meta:
model = School
fields = (‘school_founded_date’, ‘school_location’)
the output i’m trying to get is:
{
‘city_name’: ‘Boston’
‘school_founded_date’:’1957’
‘school_location’: ‘Fenway’
‘school_name’: ‘Boston Univeristy’
}
but what i’m getting is just:
{
‘city_name’:’Boston’
‘top_school’: None
}
if i change get_top_school in the CitySerializer to use obj.top_school.all() and return SchoolSerializer(top_school, read_only=True, many=True).data. It shows a nested object:
{
‘city_name’: ‘Boston’
top_school: [{
‘school_founded_date’:’1957’
‘school_location’: ‘Fenway’
‘school_name’: ‘Boston Univeristy’
}]
}
Is there a way to un-nest this?