3👍
✅
The reason you only get the slugs of the related Country
s is because you use the SlugRelatedField
, that will thus list the slugs of the Country
s.
The trick is to make extra serializers that will serializer the related object(s). For example:
class ShallowRegionSerializer(serializers.ModelSerializer):
class Meta:
model = Region
fields = '__all__'
class CountrySerializer(serializers.ModelSerializer):
region_id = ShallowRegionSerializer()
class Meta:
model = Country
fields = '__all__'
class CountryRegionSerializer(serializers.ModelSerializer):
class Meta:
model = Country
fields = '__all__'
class RegionSerializer(serializers.ModelSerializer):
countries = CountryRegionSerializer(
many=True,
read_only=True
)
class Meta:
model = Region
fields = ['id', 'region_name', 'countries']
Now you can make use of the CountrySerializer
and the RegionSerializer
. When serializing objects, it will use other serializers, like the ShallowRegionSerializer
and CountryRegionSerializer
to serialize related object(s).
Source:stackexchange.com