gpt4 book ai didi

python - Django REST 框架 : how to substitute null with empty string?

转载 作者:太空狗 更新时间:2023-10-29 21:20:32 24 4
gpt4 key购买 nike

我有一个 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')

但是,如果图像字段为空,则显示如下

Its now showing like this in the json

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

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

最佳答案

重写 AttendanceSerializerto_representation() 方法,

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

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

更新(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):
<b>my_fields = {'field_1', 'field_2', 'field_3', 'field_4', 'field_5'}</b>
data = super().to_representation(instance)
<b>for field in my_fields:
try:
if not data[field]:
data[field] = ""
except KeyError:
pass</b>
return data

关于python - Django REST 框架 : how to substitute null with empty string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52169173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com