Storing file content in DB

前端 未结 4 981
温柔的废话
温柔的废话 2021-02-14 04:08

I am making a model in which i have a FileField. I want to store the file content in a database column, instead of file path. Any suggestions?

相关标签:
4条回答
  • 2021-02-14 04:48

    Disregard the naysayers. If you want to have full control over your content, put the files in a blob field in the database. I generally also keep the filename in a separate field, so I can reconstruct the file as necessary (that way you keep the extension, which ties it to a file type in most operating systems).

    Be sure to store the actual blob data in a separate table, only connected to your filename / extra info table via an id ... that way you don't sacrifice any performance when dealing with any information related to the file other than the content itself.

    What the naysayers fail to realize, is that databases are simply an extremely optimized form of file system. Bytes are bytes and disc sectors are disc sectors. Databases are simply much better at organizing and searching those bytes than file systems are. Not to mention, databases implement much more stringent security than most file systems and are better maintained (with backups, support staff etc.).

    0 讨论(0)
  • 2021-02-14 04:52

    I know this is an old question, but there's been some good code written since then to allow this option. Specially, see django-database-files, which will use Django's storage API to make all FileFields and ImageFields store their contents in the database. There's also a fork to cache the files locally on the filesystem, to overcome the biggest caveat of using the database, which is latency.

    0 讨论(0)
  • 2021-02-14 04:56

    Well, how about simply storing it in a Binary column? You can then store collection of bytes. And if the filename is important to you as well, you can store that in an additional name column.

    0 讨论(0)
  • 2021-02-14 05:06

    it is very easy

    just overide save method in admin

    filecontent=form.cleaned_data.get('upload_file')  
    data =filecontent.read()
    from django.db import connection
    cursor = connection.cursor()
    cursor.execute("update filecontent set filecontent=(%s) where id=(%s)",[data,obj.id])
    connection.connection.commit()
    cursor.close()
    connection.close()
    

    this will store filecontent in db column filecontent of table filecontent

    0 讨论(0)
提交回复
热议问题