0

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 Answers1

0

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.