Giri Kishore
Giri Kishore

Reputation: 31

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.

Upvotes: 1

Views: 6678

Answers (3)

Gr3at
Gr3at

Reputation: 492

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.

Upvotes: 7

Jafoor
Jafoor

Reputation: 735

SQLite is the default database system of the Django Framework. It is quite good for local servers. But, if you want to host the project in it would be better to use MySQL or PostgreSQL. My recommendation would be to use PostgreSQL. If you want to host it in Heroku, they use PostgreSQL and that is super easy. You can also use AWS, which is easy for both PostgreSQL and MySQL.

At last, my personal recommendation would be to use PostgreSQL.

Upvotes: 2

Ioan Andrei
Ioan Andrei

Reputation: 71

Generally speaking SQLite is not a great database for any serious project. You would normally use something like MongoDB or Postgres or MySQL. I think Django works quite well with PostgreSQL. SQLite is great for practice and testing or small project but once you have to scale up, you can get in trouble.

Also, like Willem said, storing images in a DB is not a good idea. Normally instances stored in a DB would have a path towards an image file stored in your computer or a key to an image stored on an image storing service like Cloudinary.

Upvotes: 0

Related Questions