2๐
โ
So basically what you have to do is create a bunch of serializers.
class MakeSerializer(serializers.ModelSerializer):
class Meta:
model = Make
fields = ('your', 'fields', 'here')
class ModelSerializer(serializers.ModelSerializer):
make = MakeSerializer(many=True, read_only=True)
class Meta:
model = Model
fields = ('name', 'just_fields_here')
class StyleSerializer(serializers.ModelSerializer):
model = ModelSerializer(many=True, read_only=True)
class Meta:
model = Style
fields = ('your_fields_here_again', )
This is how your serializers could look like in the simples way.
And this is how you could use it:
>>> make = Make.objects.create(name="Audi")
>>> model1 = Model.objects.create(make=make, name='R8')
>>> model2 = Model.objects.create(make=make, name='Q7')
>>> Style.objects.create(model=model1, name='Sport')
>>> Style.objects.create(model=model2, name='SUV')
>>> serializer = MakeSerializer(instance=make)
and by using
>>> serializer.data
you output should look like this:
{
'name': 'Audi',
'model': [{
'name': 'R8',
'style': {
'name': 'Sport'
}
},{
'name': 'Q7',
'style': {
'name': 'SUV'
}
}]
}
๐คsebb
Source:stackexchange.com