Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework: how to substitute null with empty string?

I have a model with ImageField type below:

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

A serializer that is based on the model

class AttendanceSerializer(serializers.ModelSerializer):

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

However if the imagefield is null, it shows like this

Its now showing like this in the json

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

It will show an output for face_image (ImageField) as null if it is None. What I would like is to substitute null to be an empty string like this ""

like image 700
Axil Avatar asked Sep 04 '18 15:09

Axil


Video Answer


2 Answers

You could use a SerializerMethodField.

class AttendanceSerializer(serializers.ModelSerializer):

    face_image = serializers.SerializerMethodField()

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

    def get_face_image(self, instance):
        return (instance.face_image.url if instance.face_image else '')
like image 33
AKX Avatar answered Sep 28 '22 04:09

AKX


Override the to_representation() method of AttendanceSerializer as,

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

UPDATE (11/03/2019)

I have lots of fields and its not really good idea that I repeat this code for all of them, isn't there a better way to do it for all fields?

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
like image 190
JPG Avatar answered Sep 28 '22 02:09

JPG