I know it is a bad idea to stored whole file binary into database blob column, so forgive me
I have a model defined in python code:
class UploadFile(models.Model):
id = models.AutoField(auto_created=True, primary_key=True)
FileBinary = models.FileField(blank=False, default=None)
Then I run migration
python manage.py makemigrations && python manage.py migrate
But in Mysql I have Columns:
COLUMN_NAME | DATA_TYPE |
---|---|
id | int |
FileBinary | varchar |
How I fixed the code to create blob
instead of varchar
?
2
Answers
Django does not store the content of the file in the database, that would not be very efficient: it would mean it has to be escaped when transferring it from and to the database, and would also prevent to cache parts of the file and all other advanced mechanisms the operating system provides to make working with files more efficient.
For example, if you would store a video file in the database, it would require to send the entire to the Django/Python layer, even if you plan to open the file and only process a small fragment of the video file. Databases typically are also not very good in storing huge blobs: it would reduce the effectiveness of caches if the records are quite large, and thus one record would swap out other records.
It saves the file in the file system of the host system (or you can store it at some storage service like Amazone s3) and it stores the path to the file in memory.
If you really want to store the content of the file in the database, you can use a
BinaryField
[Django-doc], but that is likely not a good idea, especially if the files are large.Check out the answer by @willeM_Van Onsem above(or below) there answer is more complete.
So the django models.FileField does not actually store the file. It holds a path to the location where the file is stored on disk. As you mentioned you dont really want to be storing this data in the database for a number of reasons. But, if you did then…
If you are looking to store the file in the database it self; your best bet is to use the models.BinaryField which can be used to hold binary data.
The below is an extract from the docs: https://docs.djangoproject.com/en/4.2/ref/models/fields/#binaryfield
In your instance you will want something like the following: Where the content of
file_data
will be the file in its binary form.