Django REST Framework: how to substitute null with empty string?
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 '')
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
Code for iteration over all fields mentioned in the Serializer Meta:
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