Skip to content
Advertisement

Storing images in sqlite – Django

I’m new to Django and databases.

Django used the sqlite database as it’s default database. Is it possible to store images in the sqlite database and display it on my webpage? I can’t find any documentation on the official Django website for it.

Advertisement

Answer

Django’s ImageField and FileField are both just links to the location where the file is actually uploaded. If you read Django’s documentation on how to use imageField you may observe a upload_to attribute.

Both Fields are implemented in Django’s ORM and are DB agnostic (i.e. should work on SQLite, MySQL or any other DB supported by Django).

You can check this out for examples on how to mange files.

The first example in the link shows a Car model and uploads the image to cars under the MEDIA_ROOT folder.

from django.db import models

class Car(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    photo = models.ImageField(upload_to='cars')

Alternative

If you really need the image to live in your database you can always utilize django’s BinaryField and save the whole image as BLOB.

from django.db import models

class Car(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    photo_as_blob = models.BinaryField()  # save photo as binary object

As you can see from other answers it is not generally considered a good practice to save big files directly in DB.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement