我目前有类似的东西
class Serializer_ListEmployee(ModelSerializer):
user = Serializer_ListUser()
class Meta:
model = modelEmployee
fields = [
'user',
'employee_image',
]
有关如何取回base64编码字符串的任何建议吗?
答案 0 :(得分:2)
如果您只想从序列化器获取base64,那么您可以执行以下操作:[在另一个答案中提到的编辑]
class EmployeeSerializer(serializers.ModelSerializer):
employee_image = serializers.SerializerMethodField(read_only=True)
class Meta:
model = modelEmployee
fields = [
'user',
'employee_zip',
'employee_image',
]
def get_employee_image(self, place):
img = open( self.employee_image.path, "rb")
data = img.read()
return "data:image/jpg;base64,%s" % data.encode('base64')
参考:http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
但是如果你想要两种方式,比如读和写,那么你可以选择这样的方式:
from django.db import models
class Photo( models.Model ):
title = models.CharField( max_length=255 )
image = models.ImageField( upload_to="photos/", max_length=255)
@property
def image_url( self ):
try:
img = open( self.image.path, "rb")
data = img.read()
return "data:image/jpg;base64,%s" % data.encode('base64')
except IOError:
return self.image.url
来源:http://www.codedependant.net/2012/04/13/increase-site-performance-with-django-base64-encod/
答案 1 :(得分:0)
为图像字段创建序列化方法。在该字段中从源读取图像并将其转换为base64字符串。
请参阅此处http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield以创建方法字段。