Django restful 序列化忽略空值或者返回空字符串方法

现在的结果是:
{
"xx": {
"aa": "0.9",
"vv": null
}
}
想要的结果是:
{
"xx": {
"aa": "0.9",
}
}
from collections import OrderedDict
from operator import itemgetter

    class Meta:
        model = xxx
        fields = ('id')

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        # Here we filter the null values and creates a new dictionary
        # We use OrderedDict like in original method
        ret = OrderedDict(filter(itemgetter(1), ret.items()))
        return ret
  • null时返回空字符串统一处理方法
     

from collections import OrderedDict


class PKOnlyObject:

    def __init__(self, pk):
        self.pk = pk

    def __str__(self):
        return "%s" % self.pk


def to_representation(self, instance):
    ret = OrderedDict()
    fields = self._readable_fields

    for field in fields:
        try:
            attribute = field.get_attribute(instance)
        except Exception as e:
            continue
        check_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else attribute
        if check_for_none is None:
            ret[field.field_name] = ''
        else:
            ret[field.field_name] = field.to_representation(attribute)

    return ret



class XXXSerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        ret = to_representation(self, instance)
        return ret

 

你可能感兴趣的:(Django,Python,序列化)