如何替换Serializer中的密钥名称?

时间:2017-12-27 05:22:27

标签: python django django-rest-framework

我有一个ModelSerializer:

class PublicNetwokSerializer(ModelSerializer):
    """
    PublicNetwok
    """
    class Meta:
        model = PublicNetwok
        fields = "__all__"

该模型如下:

class PublicNetwok(models.Model):
    name = models.CharField(max_length=12)
    desc = models.CharField(max_length=24)
    ...

你知道如果我使用ModelSerializer,我将获得所有键值,如下面的:

[
 {
  "name":"xxx",
  "desc":"xxx",
 },
 {
  "name":"xxx",
  "desc":"xxx",
 }
]

但我想将密钥desc更改为description,在Django-Rest-Framework中如何访问它?

1 个答案:

答案 0 :(得分:0)

class PublicNetwokSerializer(ModelSerializer):
    description = serializers.SerializerMethodField('get_alternate_name')

    class Meta:
        model = PublicNetwok
        fields = ('name', 'description')

    def get_alternate_name(self, obj):
        return obj.desc