英文:
How to get an ImageField as datauri instead of an URL with Django Rest Framework
问题
Here is the translation of the code you provided:
我有这个models.py:
```python
from django.db import models
class Prato(models.Model):
imagem = models.ImageField()
nome = models.CharField(max_length=30)
descricao = models.TextField()
publicar = models.BooleanField()
def __str__(self):
return self.descricao
我想创建一个序列化器,返回所有字段。关键是,我希望“imagem”字段以存储图像的内联数据URI表示,而不是指向图像的URL(这将需要额外的请求来获取图像)。
这个序列化器返回图像的URL,我不知道如何只修改ImageField序列化器以返回图像的数据URI。
from rest_framework import serializers
from cardapio.models import Prato
class PratoSerializer(serializers.ModelSerializer):
class Meta:
model = Prato
fields = '__all__'
英文:
I have this models.py:
from django.db import models
class Prato(models.Model):
imagem = models.ImageField()
nome = models.CharField(max_length=30)
descricao = models.TextField()
publicar = models.BooleanField()
def __str__(self):
return self.descricao
I would like to create a serializer that returns all the fields. The trick is that I want the "imagem" field to be represented as an inline data uri of the stored image, instead of an url pointing to the image (that would demand an extra request to fetch the image).
This serializer returns the url of the image, i don know how to modify only the ImageField serializer to return data uri of image.
from rest_framework import serializers
from cardapio.models import Prato
class PratoSerializer(serializers.ModelSerializer):
class Meta:
model = Prato
fields = '__all__'
答案1
得分: 0
一种方法是使用SerializerMethodField来覆盖imagem字段的默认序列化,并在序列化时手动生成URI:
```python
import base64
from cardapio.models import Prato
from rest_framework import serializers
class PratoSerializer(serializers.ModelSerializer):
imagem = serializers.SerializerMethodField()
class Meta:
model = Prato
fields = "__all__"
def get_imagem(self, obj):
binary_fc = obj.imagem.read()
base64_utf8_str = base64.b64encode(binary_fc).decode("utf-8")
ext = obj.imagem.name.split(".")[-1]
return f"data:image/{ext};base64,{base64_utf8_str}"
有关更多详细信息,请参阅以下参考:
- https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
- https://stackoverflow.com/questions/6375942/how-do-you-base-64-encode-a-png-image-for-use-in-a-data-uri-in-a-css-file
或者,如果您希望使用第三方包,您可能还可以使用https://github.com/Hipo/drf-extra-fields中的Base64ImageField来实现类似的目标。
英文:
One approach would be to use a SerializerMethodField to override the default serialization of the imagem field and manually generate the URI at serialization time:
import base64
from cardapio.models import Prato
from rest_framework import serializers
class PratoSerializer(serializers.ModelSerializer):
imagem = serializers.SerializerMethodField()
class Meta:
model = Prato
fields = "__all__"
def get_imagem(self, obj):
binary_fc = obj.imagem.read()
base64_utf8_str = base64.b64encode(binary_fc).decode("utf-8")
ext = obj.imagem.name.split(".")[-1]
return f"data:image/{ext};base64,{base64_utf8_str}"
see these references for more detail:
- https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
- https://stackoverflow.com/questions/6375942/how-do-you-base-64-encode-a-png-image-for-use-in-a-data-uri-in-a-css-file
Alternatively, you might be able to use a Base64ImageField from https://github.com/Hipo/drf-extra-fields to accomplish a similar goal, if you want to go with a 3rd-party package.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论