实际回报
{
"store_product_mapping":{
"master_product":{
"name": "abc",
"description": "xyz"
}
}
"selling_price": 445
}
序列化器如下:
class GrandParentSerializer(serializers.ModelSerializer):
class Meta:
model = Z
fields = ('name', 'description')
class ParnetSerializer(serializers.ModelSerializer):
master_product = GrandParentSerializer(many=False, read_only=False)
class Meta:
model = Y
fields = ('master_product',)
class ChildSerializer(serializers.ModelSerializer):
store_product_mapping = ParnetSerializer(many=False, read_only=False)
class Meta:
model = X
fields = ('store_product_mapping', 'selling_price')
Am使用嵌套的rest_framework.serializer.ModelSerializer
从多个级别序列化数据,但作为响应,我需要像这样。我是否需要制作新字典并循环更新字典?还是有捷径可做?
{
"name": xyz
"description": abcd
"price": 10
}
答案 0 :(得分:4)
您可以像这样使用source
参数:
class ChildSerializer(serializers.ModelSerializer):
name = serializers.CharField(source='store_product_mapping.master_product.name')
description = serializers.CharField(source='store_product_mapping.master_product.description')
class Meta:
model = X
fields = ('name', 'description', 'selling_price')