Django REST Framework:如何用空字符串替换null?

时间:2018-09-04 15:01:39

标签: python json django django-rest-framework

我下面有一个ImageField类型的模型:

class Attendance(models.Model):
    face_image = models.ImageField(, blank=True, null=True, storage=MediaStorage())

基于模型的序列化器

class AttendanceSerializer(serializers.ModelSerializer):

    class Meta:
        model = Attendance
        fields = ('id','face_image')

但是,如果imagefield为null,则显示为

Its now showing like this in the json

  {
    "id": 1,
    "face_image": null
  }

如果为None,它将显示face_image(ImageField)的输出为null。我想要的是将null替换为这样的空字符串,例如“”

4 个答案:

答案 0 :(得分:11)

to_representation() AttendanceSerializer 方法替换为

class AttendanceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Attendance
        fields = ('id', 'face_image')

    def to_representation(self, instance):
        data = super().to_representation(instance)
        if not data['face_image']:
            data['face_image'] = ""
        return data

更新(11/03/2019)

  

我有很多字段,我对所有字段重复此代码不是一个好主意,难道没有更好的方法在所有字段上做到这一点吗?

class AttendanceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Attendance
        fields = ('id', 'face_image')

    def to_representation(self, instance):
        my_fields = {'field_1', 'field_2', 'field_3', 'field_4', 'field_5'}
        data = super().to_representation(instance)
        for field in my_fields:
            try:
                if not data[field]:
                    data[field] = ""
            except KeyError:
                pass
        return data

答案 1 :(得分:3)

您可以使用SerializerMethodField。

where year in (2016, 2017) and
      not (year = 2017 and custID in ('AB17', 'AB18'))

答案 2 :(得分:1)

要添加到JPG的答案中,以下是一个mixin,它允许更轻松地重用覆盖to_representation方法的逻辑。它还可以确保这些值None不仅是 fassy

class ConvertNoneToStringSerializerMixin():
    """
    Mixin to convert None to empty strings.

    This must be added as the first inherited class. The property `Meta.none_to_str_fields` must
    be defined in order for this to have any effect. This only applies to representations,
    when we export our instance data, not when we acquire and validate data.
    """
    def get_none_to_str_fields(self):
        meta = getattr(self, 'Meta', None)
        return getattr(meta, 'none_to_str_fields', [])

    def to_representation(self, instance):
        fields = self.get_none_to_str_fields()
        data = super().to_representation(instance)

        if not fields or not isinstance(data, dict):
            return data

        for field in fields:
            if field in data and data[field] is None:
                data[field] = ''
        return data

这是您将如何使用它:

class AttendanceSerializer(ConvertNoneToStringSerializerMixin, serializers.ModelSerializer):
    class Meta:
        model = Attendance
        fields = ('id', 'face_image')
        none_to_str_fields = ('face_image', )

对于那些想知道的人,我们无法覆盖to_representation本身的Field方法,因为Serializer的核心实现将跳过从该字段调用to_representation当值为None时。因此,覆盖串行器是唯一可以实现此目的的方法。

答案 3 :(得分:0)

用于在序列化器元数据中提及的所有字段上进行迭代的代码:

def to_representation(self, instance):
    data = super().to_representation(instance)
    for key, value in data.items():
        try:
            if not value:
                data[key] = ""
        except KeyError:
            pass
    return data