如何在Django Rest Framework中将ImageField作为datauri而不是URL获取。

huangapple go评论58阅读模式
英文:

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://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:

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.

huangapple
  • 本文由 发表于 2023年5月29日 18:33:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76356587.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定