2๐
โ
You can create a SectorSerializer
which will contain a nested serializer InsectorSerializer
.
Since you are using different keys for output we can use source
to get the corresponding values from the field names.
name
key in the output corresponds to sector_mc
, so we use sector_mc
as its source
.
children
key in the output contains all the related instances for a particular Sectors
instance. We can use FOO_set
as the source for children
field. Also, since there will be multiple related instances, we pass many=True
parameter along with it.
class InsectorSerializer(serializers.ModelSerializer):
class Meta:
model = Insector
fields = ('name', 'value')
class SectorSerializer(serializers.ModelSerializer):
name = serializers.CharField(source='sector_mc') # get value from 'sector_mc'
children = InsectorSerializer(many=True, source='insector_set') # get all related instances
class Meta:
model = Sectors
fields = ('name', 'children')
๐คRahul Gupta
0๐
There was a problem in my views file while saving data to models. DRF worked fine when views problem solved.
๐คSushant
Source:stackexchange.com