Displaying images from a DB where they're stored as binary data

I have a DB where there are images stored as what I believe to be binary data (the SQL datatype says varbinary(max)). I ultimately want to be able to query these images and send them to the front end.

With django+djangorestframework, is there a clean way to show the images?

My model:

class Graphimages(models.Model):
  clientid ...
  graphimage = models.BinaryField(...)

  class Meta:
      managed = False
      db_table = 'GraphImages'
      unique_together = (('clientid', 'machinenumberid', 'measurementitemid', 'csvfilenamedate', 'graphtype'),)

My hunch is I should convert the binary data in my serializers to say, base64, then pass the base64 strings as a json response for the front end to deal with.

Is my below pseudocode a reasonable approach, or is there a better django best practices?

import base64
from someModule import someModel

model = someModel.objects.get(pk=1)

encoded = base64.b64encode(b'model.graphImage')
return jsonresponse(encoded)

I may have also done a bit too much abstraction and I’ve lost track of what I need to override in order to make this happen :sweat_smile:

class GraphImagesSerializer(serializers.ModelSerializer):

    class Meta:
        model = Graphimages
        fields = ['clientid', 'graphimage']

I assume DRF already handles most of the serialization for me when I use serializers.ModelSerializer, but I suppose I will need to start looking into how to override serialization of graphimage

Part of the problem is going to be identifying what that binary data is to be displayed. Even if you’re reasonably sure they’re all images, you may need to determine if they’re GIF, JPEG, PNG, or something else.

But yes, assuming your front end is going to know what to do with it, sending it as base64 is about as good as it’s going to get.