是否可以在django-rest-framework序列化器中动态更改字段名称?

时间:2017-04-01 12:44:22

标签: json django serialization django-rest-framework

我有ProductProductCategory型号。

假设我有ProductCategory TV,它有 SonySamsung作为其产品。我还有MobilePhone类别,其中AppleNokia为其产品。 使用DRF,我想使用序列化器获得JSON输出,类似于下面的内容:

{
    'TV': 
        [
            'Sony': 
                {
                    'price': '$100',
                    'country': 'Japan',
                },
            'Samsung': 
                {
                    'price': '$110',
                    'country': 'Korea',
                }
        ]

    'mobile_phone':
        [
            'Apple': 
                {
                    'price': '$300',
                    'country': 'USA',
                },
            'Nokia': 
                {
                    'price': '$210',
                    'country': 'Finland',
                }
        ]
}

这里的问题是序列化程序中的字段名称('TV', 'mobile_phone')必须是动态的。

我知道我可以获得以下JSON类型

{ 
    [
            {   
                'product_category': 'TV',
                'manufacturer: 'Sony',
                'price': '$100',
                'country': 'Japan',
            },
            {
                'product_category': 'TV',
                'manufacturer: 'Samgsung',
                'price': '$110',
                'country': 'Korea',
            }
    ]

    [
            {
                'product_category': 'mobile_phone',
                'manufacturer: 'Samgsung',
                'price': '$300',
                'country': 'USA',
            },
            {
                'product_category': 'mobile_phone',
                'manufacturer: 'Apple',
                'price': '$210',
                'country': 'Finland',
            }
    ]
}

class CategorySerializer(serializers.Serializer):
    product_category = serializer.CharField()
    manufacturer = serializer.CharField()
    price = serializer.CharField()
    country = serializer.CharField()

但动态变化的字段名称很难实现。有什么方法可以做到这一点吗?

1 个答案:

答案 0 :(得分:4)

您可以通过覆盖您的序列化程序的 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "SignupSegue") { DispatchQueue.main.async { let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "SignUpViewController") self.show(vc, sender: self) } } } 和默认的ListSerializer 来支持这种自定义格式:

  1. 首先,您覆盖序列化程序的to_representation

    to_representation

    这样您的序列化类别就是这种形式:

    class CategorySerializer(serializers.Serializer):
        # your fields here
    
        def to_representation(self, obj):
          return {
              obj.manufacturer: {
                 'price': obj.price,
                 'country': obj.country
              }
          }
    
  2. 然后,在您的列表前面加{ 'Sony': { 'price': '$100', 'country': 'Japan' } } ,您可以使用自定义ListSerializer 和自定义product_category

    to_representation
相关问题