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 ""
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With